云起工作室 15711107967

微信支付

1、通过地址回调获取codevar href=encodeURIComponent("回调地址")https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri="+href+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect2、通过code、appid、secret 获取openidcomposer require wechatpay/wechatpay-guzzle-middlewarecomposer require wechatpay/wechatpayuse GuzzleHttp\Exception\RequestException;use WechatPay\GuzzleMiddleware\WechatPayMiddleware;use WechatPay\GuzzleMiddleware\Util\PemUtil;use GuzzleHttp\HandlerStack;use GuzzleHttp\Client;use WeChatPay\Builder;use WeChatPay\Crypto\Rsa;public function openid($code){ // $code="031vt80w3lEGj33AFm0w37xmo42vt80S"; $secret = "e55*****8"; $appid = "appid"; $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code"; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_TIMEOUT,30); $content = curl_exec($ch); $status = (int)curl_getinfo($ch,CURLINFO_HTTP_CODE); if ($status == 404) { return $status; } curl_close($ch); return json_decode($content,true); }3、通过openid、商户号、商户API证书序列号、商户私钥、商户证书 获取 prepay_idpublic function pay($info){ $openinfo = $this->openid($info['code']); $openid = $openinfo['openid']; // 商户相关配置, $merchantId = $this->merchantId; // 商户号 $merchantSerialNumber = $this->merchantSerialNumber; // 商户API证书序列号 $merchantPrivateKey = PemUtil::loadPrivateKey(root_path().'extend/apiclient_key.pem'); // 商户私钥 // 微信支付平台证书文件路径 $wechatpayCertificate = PemUtil::loadCertificate(root_path().'extend/apiclient_cert.pem'); // 构造一个WechatPayMiddleware $wechatpayMiddleware = WechatPayMiddleware::builder() ->withMerchant($merchantId, $merchantSerialNumber, $merchantPrivateKey) // 传入商户相关配置 ->withWechatPay([ $wechatpayCertificate ]) // 可传入多个微信支付平台证书,参数类型为array ->build(); // 将WechatPayMiddleware添加到Guzzle的HandlerStack中 $stack = HandlerStack::create(); $stack->push($wechatpayMiddleware, 'wechatpay'); // 创建Guzzle HTTP Client时,将HandlerStack传入,接下来,正常使用Guzzle发起API请求,WechatPayMiddleware会自动地处理签名和验签 $client = new Client(['handler' => $stack]); // $url = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi"; // $url = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/native"; $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; try { $resp = $client->request( 'POST', $url, //请求URL [ // JSON请求体 'json' => [ "appid" => $this->appid, "mchid" => $merchantId, "description" => $info['title'], "out_trade_no" => $info['order']['order_num'], "notify_url" => $this->notifyUrl, 'amount' => [ 'total' => $info['order']['real_fee']*100, //支付金额 'currency' => 'CNY' ], 'payer' => [ "openid"=>$openid, // 支付用户在该小程序/应用下的openid ] ], 'headers' => [ 'Accept' => 'application/json' ] ] ); $statusCode = $resp->getStatusCode(); if ($statusCode == 200) { //处理成功 $res1 = $resp->getBody()->getContents(); $arr = json_decode($res1,true); $info['prepay_id'] = $arr['prepay_id']; } else if ($statusCode == 204) { //处理成功,无返回Body // echo "success"; } } catch (RequestException $e) { // 进行错误处理 if ($e->hasResponse()) { $res1 = $e->getResponse()->getBody(); echo $res1; //不知道为什么只能在这里echo出去 } return; } return $info; }4、通过 prepay_id、appid 获取签名 paySignpublic function getPaySign($order){ $merchantPrivateKeyFilePath = PemUtil::loadPrivateKey(root_path().'extend/WXChat/apiclient_key.pem'); $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath); $params = [ 'appId' => $this->appid, 'timeStamp' => $order['create_time'], 'nonceStr' => $order['order_num'], 'package' => 'prepay_id='.$order['prepay_id'], ]; $order["paySign"]=Rsa::sign( Formatter::joinedByLineFeed(...array_values($params)), $merchantPrivateKeyInstance ); return $order; }5、js拉起微信支付funName(that,order,prepay_id){          WeixinJSBridge.invoke(          'getBrandWCPayRequest', {            "appId":"appid",     //公众号ID,由商户传入                 "timeStamp":order.create_time,//"1395712654",         //时间戳,自1970年以来的秒数                 "nonceStr":order.order_num, //随机串 自己平台生成的订单号                "package":"prepay_id="+prepay_id,                 "signType":"MD5",         //微信签名方式:                 "paySign":order.paySign, //微信签名                       },          function(res){            if(res.err_msg == "get_brand_wcpay_request:ok" ){            // 使用以上方式判断前端返回,微信团队郑重提示:主动修改订单状态                  //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。                  //var url = "/api/wxowncallback?order_num="+order.order_num+"&uid="+that.$store.state.loginUser.id                  //that.$axios.get(url)            }         });      /* eslint-disable */           }6、回调 post 接收use WechatPay\GuzzleMiddleware\Util\AesUtil;public function wxCallBack(){ $cont = file_get_contents("php://input"); $result = json_decode($cont,true); if(!empty($result['resource'])){ $restr = (new AesUtil('32位APIv3密钥'))->decryptToString($result['resource']['associated_data'],$result['resource']['nonce'],$result['resource']['ciphertext']); $res = json_decode($restr,true); // $res['transaction_id'] 交易单号 // $res['out_trade_no'] 商户单号 if($res['trade_state']=="SUCCESS"){ //处理请求 exit("success"); } } exit("fail"); }