Weixin.php 11 KB

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