Weixin.php 14 KB

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