Weixin.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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\PayTrade;
  7. use app\model\api\Recharge;
  8. use app\Request;
  9. use EasyWeChat\Factory;
  10. use library\lib\weixina;
  11. use library\services\UtilService;
  12. use think\db\exception\DbException;
  13. use think\db\exception\PDOException;
  14. use think\Exception;
  15. use think\facade\Db;
  16. class Weixin extends BaseController
  17. {
  18. public function test()
  19. {
  20. $user1 = Db::name("member")->where('i_uid',1655)
  21. ->where('regtime', 'between', [1614528000, 1617206400])
  22. ->where('last_con_time','<>',0)
  23. ->column('uid');
  24. $user2 = Db::name("member")->where('i_uid',1655)
  25. ->where('regtime', 'between', [1617206400, 1619798400])
  26. ->where('last_con_time','<>',0)
  27. ->column('uid');
  28. $user = array_merge($user1,$user2);
  29. $order = Db::name("order_info")->alias('s')->join('order o',"o.id = s.o_id")->where('s.uid', 'in', $user)
  30. ->where('o.pay_time', 'between', [1617206400, 1619798400])->count();
  31. dump($order);
  32. }
  33. public function getInfo(Request $request)
  34. {
  35. $code = trim($request->get('code'));
  36. $weixinA = new weixina;
  37. $token = $weixinA->oauth_reuslt($code);
  38. try {
  39. $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='. $token['access_token']. '&openid='. $token['openid']. '&lang=zh_CN';
  40. $res = json_decode(doRequest($url, [], null, false), true);
  41. if (isset($res['errcode']) && $res['errcode'] != 0) {
  42. return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
  43. }
  44. return $res;
  45. } catch (Exception $e) {
  46. return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
  47. }
  48. }
  49. /**
  50. * @param Request $request
  51. */
  52. public function result(Request $request)
  53. {
  54. $state = trim($request->get('state'));
  55. $code = trim($request->get('code'));
  56. if (empty($state)) {
  57. exit('error');
  58. }
  59. $weixinA = new weixina;
  60. $data = $weixinA->oauth_reuslt($code);
  61. if (!empty($data['access_token'])) {
  62. $userInfo = $weixinA->userinfo($data['access_token']);
  63. $userInfo['access_token'] = $data['access_token'];
  64. $userInfo['expires_in'] = $data['expires_in'];
  65. $userInfo['time'] = time();
  66. cookie("weix_userinfo", serialize($userInfo));
  67. $url = setParam(cookie('w_url'), ['data' => json_encode($userInfo, \JSON_UNESCAPED_UNICODE)]);
  68. redirect($url)->send();
  69. } else {
  70. exit('微信授权登录失败,关闭页面重新,重新扫描!');
  71. }
  72. }
  73. public function pay(Request $request)
  74. {
  75. [$orderId, $from] = UtilService::getMore([
  76. ['order_id', '', 'empty', '参数错误'],
  77. ['from', '', 'empty', '参数错误'],
  78. ], $request, true);
  79. $order = Order::where('order_id', $orderId)->find();
  80. if (empty($order)) {
  81. return app('json')->fail('找不到订单信息');
  82. }
  83. //订单已付款
  84. if (!empty($order['is_pay'])) {
  85. return app('json')->fail('订单已经支付成功');
  86. }
  87. $config = [
  88. // 必要配置
  89. 'app_id' => 'wxa9130b2090dfb130',
  90. 'mch_id' => '1582297191',
  91. 'key' => 'fgwhdf323gewdsd83ewewhd56wrr333g', // API 密钥
  92. 'notify_url' => '',
  93. ];
  94. $app = Factory::payment($config);
  95. if ($from == 'weixin') {
  96. $result = $app->order->unify([
  97. 'body' => '支付订单',
  98. 'out_trade_no' => $order['order_id'],
  99. 'total_fee' => $order['all_price'] * 100,
  100. 'notify_url' => 'https://api.lipinwawa.com/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  101. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  102. 'openid' => 'olkUP6fDbDSQKjidMQyeQ_0TO3XE',
  103. ]);
  104. $jssdk = $app->jssdk;
  105. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  106. $json['result'] = $jsConfig;
  107. $json['type'] = 'WECHAT_PAY';
  108. } else {
  109. $result = $app->order->unify([
  110. 'body' => '支付订单',
  111. 'out_trade_no' => $order['order_id'],
  112. 'total_fee' => $order['all_price'] * 100,
  113. 'notify_url' => 'https://api.lipinwawa.com/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  114. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  115. ]);
  116. $jssdk = $app->jssdk;
  117. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  118. $json['result'] = $jsConfig;
  119. $json['type'] = 'WECHAT_H5_PAY';
  120. }
  121. return app('json')->success($json);
  122. }
  123. public function recharge(Request $request)
  124. {
  125. [$money, $from, $code] = UtilService::getMore([
  126. ['money', '', 'empty', '请选择充值金额'],
  127. ['from', '', 'empty', '参数错误'],
  128. ['code', '']
  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['status'] = '0';
  137. $d['time'] = time();
  138. $d['sassid'] = $request->site['sassid'];
  139. $d['uid'] = $request->user['uid'];
  140. $recharge->insert($d);
  141. //生成支付凭证
  142. (new PayTrade)->mkTrade([
  143. 'out_trade_no' => $d['order_id'],
  144. 'uid' => $request->user['uid'],
  145. 'tag' => 'wxpay',
  146. 'type' => 'recharge',
  147. 'money' => $money,
  148. 'content' => '会员充值' . $d['v'] . '元',
  149. 'sassid' => $request->site['sassid'],
  150. ]);
  151. Recharge::commitTrans();
  152. $config = [
  153. // 必要配置
  154. 'app_id' => 'wxa9130b2090dfb130',
  155. 'mch_id' => '1582297191',
  156. 'key' => 'fgwhdf323gewdsd83ewewhd56wrr333g', // API 密钥
  157. 'notify_url' => '',
  158. ];
  159. $app = Factory::payment($config);
  160. if ($from == 'weixin') {
  161. if ($code) {
  162. $weixinA = new weixina;
  163. $token = $weixinA->oauth_reuslt($code);
  164. $openid = $token['openid'];
  165. (new Member)->where('uid', $request->user['uid'])->save(['openid' => $openid]);
  166. } else {
  167. $openid = $request->user['openid'];
  168. }
  169. $result = $app->order->unify([
  170. 'body' => '充值余额',
  171. 'out_trade_no' => $d['order_id'],
  172. 'total_fee' => $money * 100,
  173. 'notify_url' => 'https://api.lipinwawa.com/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  174. 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
  175. 'openid' => $openid,
  176. ]);
  177. $jssdk = $app->jssdk;
  178. $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
  179. $json['result'] = $jsConfig;
  180. $json['type'] = 'WECHAT_PAY';
  181. } else {
  182. $result = $app->order->unify([
  183. 'body' => '充值余额',
  184. 'out_trade_no' => $d['order_id'],
  185. 'total_fee' => $money * 100,
  186. 'notify_url' => 'https://api.lipinwawa.com/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  187. 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
  188. ]);
  189. $json['result'] = $result;
  190. $json['type'] = 'WECHAT_H5_PAY';
  191. }
  192. return app('json')->success($json);
  193. } catch (DbException $db) {
  194. Recharge::rollbackTrans();
  195. return app('json')->fail("充值失败,请联系客服人员");
  196. }
  197. }
  198. /**
  199. * @throws \Exception
  200. */
  201. public function notify()
  202. {
  203. // 获取微信回调的数据
  204. $notifiedData = file_get_contents('php://input');
  205. //XML格式转换
  206. $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
  207. $xmlObj = json_decode(json_encode($xmlObj), true);
  208. // 当支付通知返回支付成功时
  209. if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
  210. try {
  211. $data['appid'] = $xmlObj['appid'];
  212. $data['bank_type'] = $xmlObj['bank_type'];
  213. $data['cash_fee'] = $xmlObj['cash_fee'];
  214. $data['fee_type'] = $xmlObj['fee_type'];
  215. $data['is_subscribe'] = $xmlObj['is_subscribe'];
  216. $data['mch_id'] = $xmlObj['mch_id'];
  217. $data['nonce_str'] = $xmlObj['nonce_str'];
  218. $data['openid'] = $xmlObj['openid'];
  219. $data['out_trade_no'] = $xmlObj['out_trade_no'];
  220. $data['result_code'] = $xmlObj['result_code'];
  221. $data['return_code'] = $xmlObj['return_code'];
  222. $data['sign'] = $xmlObj['sign'];
  223. $data['time_end'] = $xmlObj['time_end'];
  224. $data['total_fee'] = $xmlObj['total_fee'];
  225. $data['trade_type'] = $xmlObj['trade_type'];
  226. $data['transaction_id'] = $xmlObj['transaction_id'];
  227. $res = Db::name('wx_notify')->insertGetId($data);
  228. if ($res) {
  229. $payTrade = new PayTrade();
  230. $data2 = $payTrade->where('out_trade_no', $xmlObj['out_trade_no'])->find();
  231. if (empty($data2)) {
  232. echo 'SUCCESS';
  233. exit;
  234. }
  235. if ($data2['status'] == 1) {
  236. echo 'SUCCESS';
  237. exit;
  238. }
  239. if ($data2['type'] == 'recharge') {
  240. $recharge = new Recharge();
  241. $recharge->rechargeSuccess($xmlObj['out_trade_no']);
  242. }
  243. $payTrade->where('id', $data2['id'])->save(['status' => 1, 'pay_time' => time()]);
  244. echo 'SUCCESS';
  245. exit;
  246. }
  247. } catch (Exception $e) {
  248. @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);
  249. } catch (DbException $e) {
  250. @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);
  251. } catch (\Exception $e) {
  252. @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);
  253. }
  254. }
  255. }
  256. }