Weixin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. namespace app\api\controller\v1;
  3. use app\BaseController;
  4. use app\model\api\Member;
  5. use app\model\api\Order;
  6. use app\model\api\OrderInfo;
  7. use app\model\api\Product;
  8. use app\model\api\Recharge;
  9. use app\Request;
  10. use EasyWeChat\Factory;
  11. use library\lib\weixina;
  12. use library\services\UtilService;
  13. use library\services\MiniProgramService;
  14. use think\db\exception\DbException;
  15. use think\db\exception\PDOException;
  16. use think\Exception;
  17. use think\facade\Db;
  18. class Weixin extends BaseController
  19. {
  20. public function jssdk(Request $request){
  21. $config = [
  22. 'app_id' => config('weixin')['APPID'],
  23. 'secret' => config('weixin')['APPSECRET'],
  24. // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
  25. 'response_type' => 'array'
  26. ];
  27. $app = Factory::officialAccount($config);
  28. $apiList = ['openAddress','updateAppMessageShareData','updateTimelineShareData','onMenuShareAppMessage','onMenuShareTimeline'];
  29. $jssdk = $app->jssdk->buildConfig($apiList, $debug = false, $beta = false, $json = false, [], $url = $request->get('url'));
  30. return app('json')->success($jssdk);
  31. }
  32. /**
  33. * 公众号获取微信信息
  34. */
  35. public function getInfo(Request $request)
  36. {
  37. $code = trim($request->get('code'));
  38. $weixinA = new weixina;
  39. $token = $weixinA->oauth_reuslt($code);
  40. if (!empty($token['access_token'])) {
  41. $userInfo = $weixinA->userinfo($token['access_token']);
  42. $data['openid'] = $userInfo['openid'];
  43. $data['nickname'] = $userInfo['nickname'];
  44. $data['sex'] = $userInfo['sex'];
  45. $data['language'] = $userInfo['language'];
  46. $data['city'] = $userInfo['city'];
  47. $data['province'] = $userInfo['province'];
  48. $data['country'] = $userInfo['country'];
  49. $data['avatar'] = $userInfo['headimgurl'];
  50. (new Member)->where('uid',$request->user['uid'])->save($data);
  51. return app('json')->success([
  52. 'nickname' => $data['nickname'],
  53. 'avatar' => $data['avatar']
  54. ]);
  55. }
  56. }
  57. /**
  58. * 小程序授权登录
  59. * @param Request $request
  60. * @return mixed
  61. * @throws \Psr\SimpleCache\InvalidArgumentException
  62. * @throws \think\db\exception\DataNotFoundException
  63. * @throws \think\db\exception\ModelNotFoundException
  64. * @throws \think\exception\DbException
  65. */
  66. public function mp_auth(Request $request){
  67. $code = trim($request->post('code'));
  68. if (!$code)
  69. return app('json')->fail('授权失败,参数有误');
  70. try {
  71. $appid = "wxb4c2433f398a6a48";
  72. $secret = "3fb376e8197f3fb9670644adbcabae59";
  73. $c= file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code");
  74. dump(json_encode($c));//对JSON格式的字符串进行编码
  75. // $userInfoCong = MiniProgramService::getUserInfo($code);
  76. // $session_key = $userInfoCong['session_key'];
  77. // $openid = $userInfoCong['openid'];
  78. // $unionid = $userInfoCong['unionid'];
  79. } catch (\Exception $e) {
  80. return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
  81. }
  82. }
  83. /**
  84. * @param Request $request
  85. */
  86. public function result(Request $request)
  87. {
  88. $state = trim($request->get('state'));
  89. $code = trim($request->get('code'));
  90. if (empty($state)) {
  91. exit('error');
  92. }
  93. $weixinA = new weixina;
  94. $data = $weixinA->oauth_reuslt($code);
  95. if (!empty($data['access_token'])) {
  96. $userInfo = $weixinA->userinfo($data['access_token']);
  97. $userInfo['access_token'] = $data['access_token'];
  98. $userInfo['expires_in'] = $data['expires_in'];
  99. $userInfo['time'] = time();
  100. cookie("weix_userinfo", serialize($userInfo));
  101. $url = setParam(cookie('w_url'), ['data' => json_encode($userInfo, \JSON_UNESCAPED_UNICODE)]);
  102. redirect($url)->send();
  103. } else {
  104. exit('微信授权登录失败,关闭页面重新,重新扫描!');
  105. }
  106. }
  107. public function pay(Request $request)
  108. {
  109. [$orderId, $from] = UtilService::getMore([
  110. ['order_id', '', 'empty', '参数错误'],
  111. ['from', '', 'empty', '参数错误'],
  112. ], $request, true);
  113. $order = Order::where('order_id', $orderId)->find();
  114. if (empty($order)) {
  115. return app('json')->fail('找不到订单信息');
  116. }
  117. //订单已付款
  118. if (!empty($order['is_pay'])) {
  119. return app('json')->fail('订单已经支付成功');
  120. }
  121. $data['out_trade_no'] = $order['order_id'];
  122. $data['money'] = $order['all_price'];
  123. $data['type'] = 'order';
  124. $data['time'] = time();
  125. Db::name('wx_notify')->insert($data);
  126. $app = Factory::payment(config('weixin')['wxPay']);
  127. if ($from == 'weixin') {
  128. $result = $app->order->unify([
  129. 'body' => '支付订单',
  130. 'out_trade_no' => $order['order_id'],
  131. 'total_fee' => $order['all_price'] * 100,
  132. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  133. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  134. 'openid' => $request->user['openid']
  135. ]);
  136. $jssdk = $app->jssdk;
  137. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  138. $json['result'] = $jsConfig;
  139. $json['type'] = 'WECHAT_PAY';
  140. } else {
  141. $result = $app->order->unify([
  142. 'body' => '支付订单',
  143. 'out_trade_no' => $order['order_id'],
  144. 'total_fee' => $order['all_price'] * 100,
  145. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  146. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  147. ]);
  148. $jssdk = $app->jssdk;
  149. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  150. $json['result'] = $jsConfig;
  151. $json['type'] = 'WECHAT_H5_PAY';
  152. }
  153. return app('json')->success($json);
  154. }
  155. public function recharge(Request $request)
  156. {
  157. [$money, $from] = UtilService::getMore([
  158. ['money', '', 'empty', '请选择充值金额'],
  159. ['from', '', 'empty', '参数错误']
  160. ], $request, true);
  161. try {
  162. Recharge::beginTrans();
  163. $recharge = new Recharge();
  164. $d = [];
  165. $d['order_id'] = 'RE' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];
  166. $d['v'] = $money;
  167. $d['time'] = time();
  168. $d['uid'] = $request->user['uid'];
  169. $recharge->insert($d);
  170. //生成支付凭证
  171. $data['out_trade_no'] = $d['order_id'];
  172. $data['money'] = $money;
  173. $data['type'] = 'recharge';
  174. $data['time'] = time();
  175. Db::name('wx_notify')->insert($data);
  176. Recharge::commitTrans();
  177. $app = Factory::payment(config('weixin')['wxPay']);
  178. if ($from == 'weixin') {
  179. $result = $app->order->unify([
  180. 'body' => '充值余额',
  181. 'out_trade_no' => $d['order_id'],
  182. 'total_fee' => $money * 100,
  183. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  184. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  185. 'openid' => $request->user['openid'],
  186. ]);
  187. $jssdk = $app->jssdk;
  188. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  189. $json['result'] = $jsConfig;
  190. $json['type'] = 'WECHAT_PAY';
  191. } else {
  192. $result = $app->order->unify([
  193. 'body' => '充值余额',
  194. 'out_trade_no' => $d['order_id'],
  195. 'total_fee' => $money * 100,
  196. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  197. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  198. ]);
  199. $json['result'] = $result;
  200. $json['type'] = 'WECHAT_H5_PAY';
  201. }
  202. return app('json')->success($json);
  203. } catch (DbException $db) {
  204. Recharge::rollbackTrans();
  205. return app('json')->fail("充值失败,请联系客服人员");
  206. }
  207. }
  208. /**
  209. * @throws \Exception
  210. */
  211. public function notify()
  212. {
  213. // 获取微信回调的数据
  214. $notifiedData = file_get_contents('php://input');
  215. //XML格式转换
  216. $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
  217. $xmlObj = json_decode(json_encode($xmlObj), true);
  218. // 当支付通知返回支付成功时
  219. if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
  220. try {
  221. $data['appid'] = $xmlObj['appid'];
  222. $data['bank_type'] = $xmlObj['bank_type'];
  223. $data['cash_fee'] = $xmlObj['cash_fee'];
  224. $data['fee_type'] = $xmlObj['fee_type'];
  225. $data['is_subscribe'] = $xmlObj['is_subscribe'];
  226. $data['mch_id'] = $xmlObj['mch_id'];
  227. $data['nonce_str'] = $xmlObj['nonce_str'];
  228. $data['openid'] = $xmlObj['openid'];
  229. $data['result_code'] = $xmlObj['result_code'];
  230. $data['return_code'] = $xmlObj['return_code'];
  231. $data['sign'] = $xmlObj['sign'];
  232. $data['time_end'] = $xmlObj['time_end'];
  233. $data['total_fee'] = $xmlObj['total_fee'];
  234. $data['trade_type'] = $xmlObj['trade_type'];
  235. $data['transaction_id'] = $xmlObj['transaction_id'];
  236. $data2 = Db::name('wx_notify')->where('out_trade_no', $xmlObj['out_trade_no'])->find();
  237. if (empty($data2)) {
  238. echo 'SUCCESS';
  239. exit;
  240. }
  241. $res = Db::name('wx_notify')->where('out_trade_no',$xmlObj['out_trade_no'])->save($data);
  242. if($res){
  243. if ($data2['type'] == 'order') {
  244. $order = Order::where('order_id', $xmlObj['out_trade_no'])->find();
  245. //减库存加销量
  246. Product::where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  247. Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  248. //改订单状态
  249. Order::where('order_id', $xmlObj['out_trade_no'])->save([
  250. 'status' => 1,
  251. 'is_pay' => 1,
  252. 'pay_type' => 'weixin',
  253. 'pay_time' => time()
  254. ]);
  255. //改子订单状态
  256. OrderInfo::where('o_id', $order['id'])->save(['status' => 1,]);
  257. }
  258. if ($data2['type'] == 'recharge') {
  259. $recharge = new Recharge();
  260. $recharge->rechargeSuccess($xmlObj['out_trade_no']);
  261. }
  262. echo 'SUCCESS';
  263. exit;
  264. }
  265. } catch (Exception $e) {
  266. @file_put_contents('error.txt', '[' . date('Y-m-d') . ']Exception:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
  267. } catch (DbException $e) {
  268. @file_put_contents('error.txt', '[' . date('Y-m-d') . ']DbException:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
  269. } catch (\Exception $e) {
  270. @file_put_contents('error.txt', '[' . date('Y-m-d') . ']\Exception:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
  271. }
  272. }
  273. }
  274. }