一、参数配置
这里有两个配置
1、微信授权的配置,要用到这几个参数
2、是支付的设置
二、微信授权
1、一开始打算用easywechat来获取用户授权,但是一直不成功,所以后来只好又用回微信原生接口开发
public function oauth() { $code = input('code'); $wx_config = $this->config; if(empty($code)) {
//获取code $r_url = urlencode('http://jskj.all2best.cn/index.php/api/weixinpay/oauth');//这里一定要用urlencode, $url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wx_config['app_id']}&redirect_uri={$r_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"; header('location:' . $url1); exit(); }else {
//获取用户信息 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wx_config['app_id']}&secret={$wx_config['secret']}&code={$code}&grant_type=authorization_code"; $result = curl_client($url); $result = json_decode($result, true); if (isset($result['errcode'])) { throw new \Exception($result['errcode'] . $result['msg']); } // dump($result); Session::prefix('index_auth'); session('open_id',$result['openid']); } }
二、微信支付:用的是easywechat的统一下单接口
public function wx_pay($bill_no, $amount) { //已登录 Session::prefix('index_auth'); $openid = session('open_id');//$user->getId(); if(empty($openid)) { $this->oauth(); }$jssdk = $this->payment->jssdk;
//统一下单 $result = $this->payment->order->unify([ 'body' => 'Kingjim', 'out_trade_no' => $bill_no, 'total_fee' => (int)bcmul($amount, 100), 'notify_url' => url('http://jskj.all2best.cn/index.php/api/weixinpay/notify', '', '', true), // 支付结果通知网址,如果不设置则会使用配置里的默认地址 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型 'openid' => $openid ]); //预支付订单号prepayId, 生成支付 JS 配置 $prepayId = $result['prepay_id']; $jsApiParameters = $jssdk->bridgeConfig($prepayId); return $jsApiParameters; }
三、支付回调方法
public function notify() { try { $response = $this->payment->handlePaidNotify(function ($message, $fail) { $order = (new Order())->get_order($message['out_trade_no']); if (!$order || $order['pay_status'] == 2) { // 如果订单不存在 或者 订单已经支付过了 return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了 } if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态 if (array_get($message, 'result_code') === 'SUCCESS') { $order['pay_status'] = 2; // 更新支付状态 (new Order())::update($order, ['bill_no' => $message['out_trade_no']]); // 保存订单 //添加流水 (new Flow())->add($order['order_final_amount'], 2, 1, $message['out_trade_no']); // 用户支付失败 } elseif (array_get($message, 'result_code') === 'FAIL') { return $fail('通信失败,请稍后再通知我'); } } else { return $fail('通信失败,请稍后再通知我'); } return true; // 返回处理完成 }); $response->send(); // return $response; } catch (Exception $e) { return tips($e->getMessage()); } }
四、前端代码