微信小程序支付 php后台对接完整代码

这个代码全是干货呀,拿过来可以直接使用。小程序在调起微信支付之前需要5个参数,这时候就需要携带code向后台请求,然后后台根据code获取openid 再进行服务器之间的。。。。

 

一、准备工作

1、小程序注册,要以公司的以身份去注册一个小程序,才有微信支付权限;

2、绑定商户号。

3、在小程序填写合法域

二、完成以上条件,你可以得到

     小程序appid 小程序秘钥    这两个用于获取用户openid;

     商户号id ,商户号秘钥     支付接口必须的;

三、开始开发

前台代码

 /*
 调起微信支付 
 @param 支付价格,不填写默认为1分钱
*/
function pay(total_fee) {

  var total_fee = total_fee; 
  wx.login({
    success: res => {

       //code 用于获取openID的条件之一
      var code = res.code;
      wx.request({
        url: '后台地址/index.php',
        method: "POST",
        data: {
          total_fee:total_fee,
          code: code,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {  //后端返回的数据
          var data = res.data;
          console.log(data);
          console.log(data["timeStamp"]);
          wx.requestPayment({
            timeStamp: data['timeStamp'],
            nonceStr: data['nonceStr'],
            package: data['package'],
            signType: data['signType'],
            paySign: data['paySign'],
            success: function (res) {
              wx.showModal({
                title: '支付成功',
                content: '',
              })
            },
            fail: function (res) {
              console.log(res);
            }
          })
        }
      });


    }
  })
  
}

 

 

以下是PHP后台代码 ,这里用的是tp框架

<?php
namespace Home\Controller;
use Think\Controller;
class PayController extends Controller {

//微信支付
public function pay(){
        //获取openid
        if(I("post.code"))
        {   //用code获取openid
            $code=I("post.code");
            $WX_APPID = '';//appid
            $WX_SECRET = '';//AppSecret
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code";
            $infos = json_decode(file_get_contents($url));
            $openid = $infos->openid;
        }
    //$fee = I("post.total_fee");
    $fee = 0.01;//举例支付0.01
    $appid =        '';//appid.如果是公众号 就是公众号的appid
    $body =         '标题';
    $mch_id =       '';  //商户号
    $nonce_str =    $this->nonce_str();//随机字符串
    $notify_url =   ''; //回调的url【自己填写】
    $openid =       $openid;
    $out_trade_no = $this->order_number();//商户订单号
    $spbill_create_ip = '';//服务器的ip【自己填写】;
    $total_fee =    $fee*100;// 微信支付单位是分,所以这里需要*100
    $trade_type = 'JSAPI';//交易类型 默认


    //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
    $post['appid'] = $appid;
    $post['body'] = $body;
    $post['mch_id'] = $mch_id;
    $post['nonce_str'] = $nonce_str;//随机字符串
    $post['notify_url'] = $notify_url;
    $post['openid'] = $openid;
    $post['out_trade_no'] = $out_trade_no;
    $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
    $post['total_fee'] = $total_fee;//总金额 
    $post['trade_type'] = $trade_type;
    $sign = $this->sign($post);//签名
    $post_xml = '<xml>
           <appid>'.$appid.'</appid>
           <body>'.$body.'</body>
           <mch_id>'.$mch_id.'</mch_id>
           <nonce_str>'.$nonce_str.'</nonce_str>
           <notify_url>'.$notify_url.'</notify_url>
           <openid>'.$openid.'</openid>
           <out_trade_no>'.$out_trade_no.'</out_trade_no>
           <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
           <total_fee>'.$total_fee.'</total_fee>
           <trade_type>'.$trade_type.'</trade_type>
           <sign>'.$sign.'</sign>
        </xml> ';


    //print_r($post_xml);die;
    //统一接口prepay_id
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $xml = $this->http_request($url,$post_xml);




    $array = $this->xml($xml);//全要大写


    //print_r($array);
    if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){
        $time = time();
        $tmp='';//临时数组用于签名
        $tmp['appId'] = $appid;
        $tmp['nonceStr'] = $nonce_str;
        $tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
        $tmp['signType'] = 'MD5';
        $tmp['timeStamp'] = "$time";


        $data['state'] = 200;
        $data['timeStamp'] = "$time";//时间戳
        $data['nonceStr'] = $nonce_str;//随机字符串
        $data['signType'] = 'MD5';//签名算法,暂支持 MD5
        $data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
        $data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
        $data['out_trade_no'] = $out_trade_no;


    }else{
        $data['state'] = 0;
        $data['text'] = "错误";
        $data['RETURN_CODE'] = $array['RETURN_CODE'];
        $data['RETURN_MSG'] = $array['RETURN_MSG'];
    }


    echo json_encode($data);
}




//随机32位字符串
private function nonce_str(){
    $result = '';
    $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
    for ($i=0;$i<32;$i++){
        $result .= $str[rand(0,48)];
    }
    return $result;
}



//生成订单号
private function order_number($openid){
    //date('Ymd',time()).time().rand(10,99);//18位
    return md5($openid.time().rand(10,99));//32位
}



//签名 $data要先排好顺序
private function sign($data){
    $stringA = '';
    foreach ($data as $key=>$value){
        if(!$value) continue;
        if($stringA) $stringA .= '&'.$key."=".$value;
        else $stringA = $key."=".$value;
    }
    $wx_key = '';//申请支付后有给予一个商户账号和密码,登陆后自己设置的key
    $stringSignTemp = $stringA.'&key='.$wx_key;
    return strtoupper(md5($stringSignTemp));
}


//curl请求
public function http_request($url,$data = null,$headers=array())
{
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);


    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}


//获取xml
private function xml($xml){
    $p = xml_parser_create();
    xml_parse_into_struct($p, $xml, $vals, $index);
    xml_parser_free($p);
    $data = "";
    foreach ($index as $key=>$value) {
        if($key == 'xml' || $key == 'XML') continue;
        $tag = $vals[$value[0]]['tag'];
        $value = $vals[$value[0]]['value'];
        $data[$tag] = $value;
    }
    return $data;
}



} 

权声明:本文为博主原创文章,转载此文章须经博主同意,并请附上原文链接, https://blog.csdn.net/weixin_42237632/article/details/80648927

 

 

 

 

 

  • 19
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 46
    评论
### 回答1: 微信小程序支付api-v3是微信提供的一种支付方式,它基于RESTful风格的API设计,使用HTTP协议传输数据,全部使用JSON格式,具有优秀的跨平台性能和安全性。本文将为大家提供微信小程序支付api-v3 php完整代码微信小程序支付api-v3 php完整代码: 首先,需要获取商户的API密钥和证书文件,然后设置请求头信息,代码如下: $merchant_api_secret = 'Your Secret Key'; //商户API密钥 $merchant_cert_file = 'path/to/cert.pem'; //商户证书文件路径 $merchant_key_file = 'path/to/key.pem'; //商户密钥文件路径 $timestamp = time(); $nonce_str = uniqid(); $signature = generate_signature($merchant_api_secret, $timestamp, $nonce_str, $http_method, $http_uri, $query_string, $body); $header = array( 'Authorization: ' . $authorization, 'Accept: application/json', 'Content-Type: application/json', 'User-Agent: your-device', 'Wechatpay-Serial: your-certificate-serial-number', 'Wechatpay-Timestamp: ' . $timestamp, 'Wechatpay-Nonce: ' . $nonce_str, 'Wechatpay-Signature: ' . $signature, ); 然后,我们需要调用微信小程序支付api-v3接口,具体如下: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); curl_setopt($ch, CURLOPT_SSLCERT, $merchant_cert_file); curl_setopt($ch, CURLOPT_SSLKEY, $merchant_key_file); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method); if (!empty($body)){ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); } $response = curl_exec($ch); $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status_code !== 200){ throw new Exception('微信小程序支付api-v3调用错误,错误代码' . $status_code); } $response_payload = json_decode($response, true); curl_close($ch); 以上就是微信小程序支付api-v3 php完整代码,通过以上代码可以实现微信小程序支付api-v3的接口调用,实现支付等操作。同时需要注意的是,具体代码需要根据自己的实际情况进行调整。 ### 回答2: 微信小程序支付API-v3是一套用于支付的接口,支持PHP语言,这里提供完整的代码实现。 在使用微信小程序支付API-v3前需要进行身份验证,将私钥转换为PKCS8格式和获取API证书,并将两者合成一个PEM格式的文件。接下来就可以创建支付订单并进行支付了。 以下是PHP代码的示例: ```php <?php require_once "wxpayloader.php"; $wxpayConfig = new WxPayConfig(); // 公众号ID $wxpayConfig->setAppId("your app id"); // 商户号 $wxpayConfig->setMchId("your mch id"); // 商户API秘钥 $wxpayConfig->setApiKey("your api key"); // 商户API证书路径 $wxpayConfig->setSslCertPath("path/to/your/apiclient_cert.pem"); // 商户API证书密钥路径 $wxpayConfig->setSslKeyPath("path/to/your/apiclient_key.pem"); // 微信支付平台API证书路径 $wxpayConfig->setSslRootCaPath("path/to/your/rootca.pem"); // 接口请求地址 $wxpayConfig->setApiUrl("https://api.mch.weixin.qq.com/"); // 验证商户API证书 $result = WxPayApi::sslVerify($wxpayConfig); if($result['result'] != 0) { die("SSL证书验证失败:" . $result['errmsg']); } // 创建订单 $out_trade_no = "20170525" . rand(10000, 99999); $total_fee = 1; $trade_type = "JSAPI"; // 交易类型为小程序支付 $notify_url = "http://your.domain.com/weixin/paynotify.php"; // 支付结果通知URL $wxpayData = new WxPayData(); $wxpayData->setBody("test"); $wxpayData->setOutTradeNo($out_trade_no); $wxpayData->setTotalFee($total_fee); $wxpayData->setTradeType($trade_type); $wxpayData->setNotifyUrl($notify_url); $wxpayData->setOpenid("your openid"); // 用户的openid,小程序通过wx.login获取 // 统一下单 $result = WxPayApi::unifiedOrder($wxpayConfig, $wxpayData); if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') { die("统一下单失败:" . $result['err_code_des']); } // 获取微信小程序支付参数 $prepay_id = $result["prepay_id"]; $wxpayData = new WxPayData(); $wxpayData->setAppId($wxpayConfig->getAppId()); $wxpayData->setTimeStamp(time()); $wxpayData->setNonceStr(WxPayApi::generateNonceStr()); $wxpayData->setPackage("prepay_id=" . $prepay_id); $wxpayData->setSignType("RSA"); // 生成签名 $sign = WxPayApi::generateSignature($wxpayData, $wxpayConfig); // 将签名加到数据包中 $wxpayData->setPaySign($sign); // 返回小程序支付参数 echo json_encode($wxpayData->getValues()); ``` 以上代码首先创建了WxPayConfig对象,将商户号、API密钥、API证书路径等信息设置进去。然后创建订单数据包,通过WxPayApi::unifiedOrder方法提交到微信支付平台统一下单。如果成功,则获取预支付ID,按照微信小程序支付的规定生成签名,再将签名加到数据包中,最终返回给小程序,由小程序前端发起支付请求。 获取API证书和PKCS8格式私钥的方法,请参考微信支付平台官方文档。 ### 回答3: 微信小程序支付 API-v3 提供了一种安全、高效、简便的支付方式,帮助开发者更好地满足用户需求。以下是微信小程序支付 API-v3 PHP 完整代码。 首先,要使用微信小程序支付 API-v3,需要先在微信支付商户平台上注册并开通服务。 接下来,下载 PHP SDK 安装包,将下载得到的文件解压后,将文件夹内的文件复制到项目代码所在的目录中。 在代码中导入 SDK 中的类库: ```php require_once "lib/WxPay.Api.php"; require_once "lib/WxPay.Data.php"; ``` 接着,需要通过商户号和 API 密钥进行身份验证: ```php $config = new WxPayConfig(); $config->SetMerchantId("商户号"); $config->SetKey("API密钥"); ``` 然后,实例化一个统一下单对象,并设置相关支付参数: ```php $input = new WxPayUnifiedOrder(); $input->SetBody("商品描述"); // 商品描述 $input->SetAttach("附加数据"); // 附加数据 $input->SetOut_trade_no("商户订单号"); // 商户订单号 $input->SetNotify_url("回调URL"); // 回调URL $input->SetTotal_fee("总金额"); // 总金额(单位:分) $input->SetTrade_type("JSAPI"); // 交易类型 $input->SetOpenid("用户openid"); // 用户openid ``` 接着,调用统一下单 API 并获取支付参数: ```php $order = WxPayApi::unifiedOrder($config, $input); $prepayId = $order["prepay_id"]; $nonceStr = WxPayApi::getNonceStr(); $timeStamp = time(); $package = "prepay_id=" . $prepayId; $signType = "HMAC-SHA256"; $paySign = WxPayApi::getPaySign($config, $nonceStr, $package, $signType, $timeStamp); ``` 最后,在前端页面中使用获取到的支付参数调起微信支付即可。
评论 46
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值