实现微信支付需要在微信商户平台和微信公众平台中做好配置。
1、到微信商户平台中去开通jsapi支付(产品中心-JSAPI支付-申请开通)
2、微信商户平台中下载证书以及设置api密钥(这里我使用的是v2 密钥)(账户中心-api安全),查看指引中很详细的说明了下载证书以及设置密钥的步骤。
3、微信商户平台中设置网页授权支付和支付回调url(产品中心-JSAPI支付-开发配置)
4、微信公众平台中配置appid,AppSecret,IP白名单(基本配置)
5、微信公众平台中设置网页授权域名。这里是前端的授权域名及后端的接口授权(公众号设置-功能设置-网页授权域名)
6、微信公众平台中关联商户号,点击关联商户号会自动跳转微信商户平台中,填写相关配置后返回公众平台点击授权就可以了(微信支付-商户号管理-关联更多商户号)
准备开发---
1、配置 appid,商户号,key,及下载好的api证书(我的配置写在config中wechat.php)
return [ 'app_id' => 'XXXXXXXXXXXXX',//appid 'mch_id' => 'xxxxxxxxxxx',//商户号 'key' => 'xxxxxxxxxxxxxxxxxxxx', // API v2 密钥 // 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书) 'cert_path' => ROOT_PATH.'cert/apiclient_cert.pem', // XXX: 绝对路径!!!! 'key_path' => ROOT_PATH.'cert/apiclient_key.pem', // XXX: 绝对路径!!!! 'notify_url'=> '默认的订单回调地址', ];
2、编写接口配合前端获取openid(前端传递code,获取opedid)
private $appid = 'xxxxxxxxxxxxx'; private $appsecrt = 'xxxxxxxxxxxxxxxxxxxxxxxxx'; /** * 获取用户openid */ public function getUserOpenid(){ $code = $this->request->post('code'); $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appsecrt . "&code=$code&grant_type=authorization_code"; $r = MCurl::instance($url)->get(); $openid=json_decode($r,true); return json($openid); }
3、后端代码(这里支付请求通过微信的SDK来进行)上代码
use EasyWeChat\Factory; use EasyWeChat\Payment\Application; use EasyWeChat\Payment\Order\Client;
参数:openid,订单编号,金额,json数据
protected function wechatPay($open_id, $out_trade_no, $amount, $attach, $body = "测试") { $options = Config::get('wechat'); $payment = Factory::payment($options); $attribute = [ "body" => $body, "out_trade_no" => $out_trade_no, "total_fee" => $amount * 100, "notify_url" => url("user/wechatNotify", [], true, true)->build(), 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型 'openid' => $open_id, 'attach' => $attach, 'sign_type' => 'MD5' ]; $res = $payment->order->unify($attribute); if ($res['return_code'] == "SUCCESS" && $res['result_code'] == "SUCCESS") { $jssdk = $payment->jssdk; $json = $jssdk->bridgeConfig($res['prepay_id'], false); // 返回 json 字符串,如果想返回数组,传第二个参数 false return $json; } else { return false; } }
4、设置支付回调
public function wechatNotify() { Log::info("wechatNotify:" . file_get_contents("php://input")); $options = Config::get("wechat"); $payment = Factory::payment($options); try { $response = $payment->handlePaidNotify(function ($message, $fail) { Log::info("wechatNotify:", $message); //执行回调逻辑,根据实际情况编写 $result = $this->notify($message["out_trade_no"], $message["transaction_id"], $message['attach']); if ($result) { return true; } else { $fail("订单处理失败"); } }); $response->send(); // return $response; } catch (\Exception $e) { Log::info("微信回调异常:" . $e->getMessage()); } }
、、、、、
在支付测试中遇到,安卓可以成功唤起支付,但是ios不可以,报错当前页面的url未注册,
解决:原理:单页应用,ios系统获取签名的url是首次进入页面的地址,安卓系统获取的是当前页面的url地址(可以度娘解决方案很多)