Weixin.php 13 KB

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