Weixin.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. $member = (new Member)->where('uid',$request->user['uid'])->find();
  43. if($member['routine_openid']){
  44. (new Member)->where('uid',$request->user['uid'])->save(['openid' => $userInfo['openid']]);
  45. }else{
  46. $data['openid'] = $userInfo['openid'];
  47. $data['nickname'] = $userInfo['nickname'];
  48. $data['sex'] = $userInfo['sex'];
  49. $data['language'] = $userInfo['language'];
  50. $data['city'] = $userInfo['city'];
  51. $data['province'] = $userInfo['province'];
  52. $data['country'] = $userInfo['country'];
  53. $data['avatar'] = $userInfo['headimgurl'];
  54. (new Member)->where('uid',$request->user['uid'])->save($data);
  55. }
  56. return app('json')->success([
  57. 'nickname' => $data['nickname'],
  58. 'avatar' => $data['avatar']
  59. ]);
  60. }
  61. }
  62. /**
  63. * 小程序授权登录
  64. * @param Request $request
  65. * @return mixed
  66. * @throws \Psr\SimpleCache\InvalidArgumentException
  67. * @throws \think\db\exception\DataNotFoundException
  68. * @throws \think\db\exception\ModelNotFoundException
  69. * @throws \think\exception\DbException
  70. */
  71. public function mp_auth(Request $request){
  72. $post = UtilService::getMore([
  73. ['code', '', 'empty', '参数错误'],
  74. ['iv', ''],
  75. ['encryptedData', ''],
  76. ]);
  77. try {
  78. $mini = Factory::miniProgram(config('weixin')['mini_program']);
  79. $new_mini = $mini->auth->session($post['code']);
  80. $member = (new Member)->where('uid',$request->user['uid'])->find();
  81. if($member['openid']){
  82. (new Member)->where('uid',$request->user['uid'])->save(['routine_openid' => $new_mini['openid']]);
  83. }else{
  84. $userInfo = $mini->encryptor->decryptData($new_mini['session_key'], $post['iv'], $post['encryptedData']);
  85. $data['routine_openid'] = $new_mini['openid'];
  86. $data['nickname'] = $userInfo['nickName'];
  87. $data['sex'] = $userInfo['gender'];
  88. $data['language'] = $userInfo['language'];
  89. $data['city'] = $userInfo['city'];
  90. $data['province'] = $userInfo['province'];
  91. $data['country'] = $userInfo['country'];
  92. $data['avatar'] = $userInfo['avatarUrl'];
  93. (new Member)->where('uid',$request->user['uid'])->save($data);
  94. return app('json')->success([
  95. 'nickname' => $data['nickname'],
  96. 'avatar' => $data['avatar']
  97. ]);
  98. }
  99. } catch (\Exception $e) {
  100. return app('json')->fail('获取session_key失败', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
  101. }
  102. }
  103. /**
  104. * @param Request $request
  105. */
  106. public function result(Request $request)
  107. {
  108. $state = trim($request->get('state'));
  109. $code = trim($request->get('code'));
  110. if (empty($state)) {
  111. exit('error');
  112. }
  113. $weixinA = new weixina;
  114. $data = $weixinA->oauth_reuslt($code);
  115. if (!empty($data['access_token'])) {
  116. $userInfo = $weixinA->userinfo($data['access_token']);
  117. $userInfo['access_token'] = $data['access_token'];
  118. $userInfo['expires_in'] = $data['expires_in'];
  119. $userInfo['time'] = time();
  120. cookie("weix_userinfo", serialize($userInfo));
  121. $url = setParam(cookie('w_url'), ['data' => json_encode($userInfo, \JSON_UNESCAPED_UNICODE)]);
  122. redirect($url)->send();
  123. } else {
  124. exit('微信授权登录失败,关闭页面重新,重新扫描!');
  125. }
  126. }
  127. public function pay(Request $request)
  128. {
  129. [$orderId, $from] = UtilService::getMore([
  130. ['order_id', '', 'empty', '参数错误'],
  131. ['from', '', 'empty', '参数错误'],
  132. ], $request, true);
  133. $order = Order::where('order_id', $orderId)->find();
  134. if (empty($order)) {
  135. return app('json')->fail('找不到订单信息');
  136. }
  137. //订单已付款
  138. if (!empty($order['is_pay'])) {
  139. return app('json')->fail('订单已经支付成功');
  140. }
  141. $data['out_trade_no'] = $order['order_id'];
  142. $data['money'] = $order['all_price'];
  143. $data['type'] = 'order';
  144. $data['time'] = time();
  145. Db::name('wx_notify')->insert($data);
  146. if ($from == 'weixin') {
  147. $app = Factory::payment(config('weixin')['wxPay']);
  148. $result = $app->order->unify([
  149. 'body' => '支付订单',
  150. 'out_trade_no' => $order['order_id'],
  151. 'total_fee' => $order['all_price'] * 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. }
  161. if ($from == 'h5') {
  162. $app = Factory::payment(config('weixin')['wxPay']);
  163. $result = $app->order->unify([
  164. 'body' => '支付订单',
  165. 'out_trade_no' => $order['order_id'],
  166. 'total_fee' => $order['all_price'] * 100,
  167. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  168. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  169. ]);
  170. $jssdk = $app->jssdk;
  171. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  172. $json['result'] = $jsConfig;
  173. $json['type'] = 'WECHAT_H5_PAY';
  174. }
  175. if ($from == 'routine') {
  176. $app = Factory::payment(config('weixin')['routinePay']);
  177. $result = $app->order->unify([
  178. 'body' => '支付订单',
  179. 'out_trade_no' => $order['order_id'],
  180. 'total_fee' => $order['all_price'] * 100,
  181. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  182. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  183. 'openid' => $request->user['routine_openid']
  184. ]);
  185. $jssdk = $app->jssdk;
  186. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  187. $json['result'] = $jsConfig;
  188. $json['type'] = 'ROUTINE_PAY';
  189. }
  190. return app('json')->success($json);
  191. }
  192. public function recharge(Request $request)
  193. {
  194. [$money, $from] = UtilService::getMore([
  195. ['money', '', 'empty', '请选择充值金额'],
  196. ['from', '', 'empty', '参数错误']
  197. ], $request, true);
  198. try {
  199. Recharge::beginTrans();
  200. $recharge = new Recharge();
  201. $d = [];
  202. $d['order_id'] = 'RE' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];
  203. $d['v'] = $money;
  204. $d['time'] = time();
  205. $d['uid'] = $request->user['uid'];
  206. $recharge->insert($d);
  207. //生成支付凭证
  208. $data['out_trade_no'] = $d['order_id'];
  209. $data['money'] = $money;
  210. $data['type'] = 'recharge';
  211. $data['time'] = time();
  212. Db::name('wx_notify')->insert($data);
  213. Recharge::commitTrans();
  214. $app = Factory::payment(config('weixin')['wxPay']);
  215. if ($from == 'weixin') {
  216. $result = $app->order->unify([
  217. 'body' => '充值余额',
  218. 'out_trade_no' => $d['order_id'],
  219. 'total_fee' => $money * 100,
  220. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  221. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  222. 'openid' => $request->user['openid'],
  223. ]);
  224. $jssdk = $app->jssdk;
  225. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  226. $json['result'] = $jsConfig;
  227. $json['type'] = 'WECHAT_PAY';
  228. } else {
  229. $result = $app->order->unify([
  230. 'body' => '充值余额',
  231. 'out_trade_no' => $d['order_id'],
  232. 'total_fee' => $money * 100,
  233. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  234. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  235. ]);
  236. $json['result'] = $result;
  237. $json['type'] = 'WECHAT_H5_PAY';
  238. }
  239. return app('json')->success($json);
  240. } catch (DbException $db) {
  241. Recharge::rollbackTrans();
  242. return app('json')->fail("充值失败,请联系客服人员");
  243. }
  244. }
  245. /**
  246. * @throws \Exception
  247. */
  248. public function notify()
  249. {
  250. // 获取微信回调的数据
  251. $notifiedData = file_get_contents('php://input');
  252. //XML格式转换
  253. $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
  254. $xmlObj = json_decode(json_encode($xmlObj), true);
  255. // 当支付通知返回支付成功时
  256. if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
  257. try {
  258. $data['appid'] = $xmlObj['appid'];
  259. $data['bank_type'] = $xmlObj['bank_type'];
  260. $data['cash_fee'] = $xmlObj['cash_fee'];
  261. $data['fee_type'] = $xmlObj['fee_type'];
  262. $data['is_subscribe'] = $xmlObj['is_subscribe'];
  263. $data['mch_id'] = $xmlObj['mch_id'];
  264. $data['nonce_str'] = $xmlObj['nonce_str'];
  265. $data['openid'] = $xmlObj['openid'];
  266. $data['result_code'] = $xmlObj['result_code'];
  267. $data['return_code'] = $xmlObj['return_code'];
  268. $data['sign'] = $xmlObj['sign'];
  269. $data['time_end'] = $xmlObj['time_end'];
  270. $data['total_fee'] = $xmlObj['total_fee'];
  271. $data['trade_type'] = $xmlObj['trade_type'];
  272. $data['transaction_id'] = $xmlObj['transaction_id'];
  273. $data2 = Db::name('wx_notify')->where('out_trade_no', $xmlObj['out_trade_no'])->find();
  274. if (empty($data2)) {
  275. echo 'SUCCESS';
  276. exit;
  277. }
  278. $res = Db::name('wx_notify')->where('out_trade_no',$xmlObj['out_trade_no'])->save($data);
  279. if($res){
  280. if ($data2['type'] == 'order') {
  281. $order = Order::where('order_id', $xmlObj['out_trade_no'])->find();
  282. //减库存加销量
  283. Product::where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  284. Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  285. //改订单状态
  286. Order::where('order_id', $xmlObj['out_trade_no'])->save([
  287. 'status' => 1,
  288. 'is_pay' => 1,
  289. 'pay_type' => 'weixin',
  290. 'pay_time' => time()
  291. ]);
  292. //改子订单状态
  293. OrderInfo::where('o_id', $order['id'])->save(['status' => 1,]);
  294. }
  295. if ($data2['type'] == 'recharge') {
  296. $recharge = new Recharge();
  297. $recharge->rechargeSuccess($xmlObj['out_trade_no']);
  298. }
  299. echo 'SUCCESS';
  300. exit;
  301. }
  302. } catch (Exception $e) {
  303. @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);
  304. } catch (DbException $e) {
  305. @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);
  306. } catch (\Exception $e) {
  307. @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);
  308. }
  309. }
  310. }
  311. }