Weixin.php 11 KB

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