Weixin.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. $app = Factory::payment(config('weixin')['wxPay']);
  147. if ($from == 'weixin') {
  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. } else {
  161. $result = $app->order->unify([
  162. 'body' => '支付订单',
  163. 'out_trade_no' => $order['order_id'],
  164. 'total_fee' => $order['all_price'] * 100,
  165. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  166. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  167. ]);
  168. $jssdk = $app->jssdk;
  169. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  170. $json['result'] = $jsConfig;
  171. $json['type'] = 'WECHAT_H5_PAY';
  172. }
  173. return app('json')->success($json);
  174. }
  175. public function recharge(Request $request)
  176. {
  177. [$money, $from] = UtilService::getMore([
  178. ['money', '', 'empty', '请选择充值金额'],
  179. ['from', '', 'empty', '参数错误']
  180. ], $request, true);
  181. try {
  182. Recharge::beginTrans();
  183. $recharge = new Recharge();
  184. $d = [];
  185. $d['order_id'] = 'RE' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];
  186. $d['v'] = $money;
  187. $d['time'] = time();
  188. $d['uid'] = $request->user['uid'];
  189. $recharge->insert($d);
  190. //生成支付凭证
  191. $data['out_trade_no'] = $d['order_id'];
  192. $data['money'] = $money;
  193. $data['type'] = 'recharge';
  194. $data['time'] = time();
  195. Db::name('wx_notify')->insert($data);
  196. Recharge::commitTrans();
  197. $app = Factory::payment(config('weixin')['wxPay']);
  198. if ($from == 'weixin') {
  199. $result = $app->order->unify([
  200. 'body' => '充值余额',
  201. 'out_trade_no' => $d['order_id'],
  202. 'total_fee' => $money * 100,
  203. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  204. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  205. 'openid' => $request->user['openid'],
  206. ]);
  207. $jssdk = $app->jssdk;
  208. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  209. $json['result'] = $jsConfig;
  210. $json['type'] = 'WECHAT_PAY';
  211. } else {
  212. $result = $app->order->unify([
  213. 'body' => '充值余额',
  214. 'out_trade_no' => $d['order_id'],
  215. 'total_fee' => $money * 100,
  216. 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  217. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  218. ]);
  219. $json['result'] = $result;
  220. $json['type'] = 'WECHAT_H5_PAY';
  221. }
  222. return app('json')->success($json);
  223. } catch (DbException $db) {
  224. Recharge::rollbackTrans();
  225. return app('json')->fail("充值失败,请联系客服人员");
  226. }
  227. }
  228. /**
  229. * @throws \Exception
  230. */
  231. public function notify()
  232. {
  233. // 获取微信回调的数据
  234. $notifiedData = file_get_contents('php://input');
  235. //XML格式转换
  236. $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
  237. $xmlObj = json_decode(json_encode($xmlObj), true);
  238. // 当支付通知返回支付成功时
  239. if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
  240. try {
  241. $data['appid'] = $xmlObj['appid'];
  242. $data['bank_type'] = $xmlObj['bank_type'];
  243. $data['cash_fee'] = $xmlObj['cash_fee'];
  244. $data['fee_type'] = $xmlObj['fee_type'];
  245. $data['is_subscribe'] = $xmlObj['is_subscribe'];
  246. $data['mch_id'] = $xmlObj['mch_id'];
  247. $data['nonce_str'] = $xmlObj['nonce_str'];
  248. $data['openid'] = $xmlObj['openid'];
  249. $data['result_code'] = $xmlObj['result_code'];
  250. $data['return_code'] = $xmlObj['return_code'];
  251. $data['sign'] = $xmlObj['sign'];
  252. $data['time_end'] = $xmlObj['time_end'];
  253. $data['total_fee'] = $xmlObj['total_fee'];
  254. $data['trade_type'] = $xmlObj['trade_type'];
  255. $data['transaction_id'] = $xmlObj['transaction_id'];
  256. $data2 = Db::name('wx_notify')->where('out_trade_no', $xmlObj['out_trade_no'])->find();
  257. if (empty($data2)) {
  258. echo 'SUCCESS';
  259. exit;
  260. }
  261. $res = Db::name('wx_notify')->where('out_trade_no',$xmlObj['out_trade_no'])->save($data);
  262. if($res){
  263. if ($data2['type'] == 'order') {
  264. $order = Order::where('order_id', $xmlObj['out_trade_no'])->find();
  265. //减库存加销量
  266. Product::where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  267. Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
  268. //改订单状态
  269. Order::where('order_id', $xmlObj['out_trade_no'])->save([
  270. 'status' => 1,
  271. 'is_pay' => 1,
  272. 'pay_type' => 'weixin',
  273. 'pay_time' => time()
  274. ]);
  275. //改子订单状态
  276. OrderInfo::where('o_id', $order['id'])->save(['status' => 1,]);
  277. }
  278. if ($data2['type'] == 'recharge') {
  279. $recharge = new Recharge();
  280. $recharge->rechargeSuccess($xmlObj['out_trade_no']);
  281. }
  282. echo 'SUCCESS';
  283. exit;
  284. }
  285. } catch (Exception $e) {
  286. @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);
  287. } catch (DbException $e) {
  288. @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);
  289. } catch (\Exception $e) {
  290. @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);
  291. }
  292. }
  293. }
  294. }