PHP实现小程序微信支付V2获取prepay_id

本文简要介绍如何使用PHP实现小程序微信支付V2中获取prepay_id的流程,包括小程序端的JS代码和PHP服务器端的处理代码。在PHP代码中,特别指出appid的小写i是关键,否则会导致签名验证失败。建议读者参考微信支付开发者文档以获取更全面的支付流程。

PS:本文旨在简单获取prepay_id,只是简单的介绍一下流程,并非完整的订单支付流程

小程序端JS代码:

  getxml(){
    var test = this
   wx.getStorage({    //从缓存中获取用户的openid
      key:'openid',
      success(res){
        console.log(res)
        test.setData({
          'openid':res.data
        })
        console.log(test.data.openid)
      }
    })
    wx.request({
      url: 'http://', //你的URl地址
      method:'POST',
      header:{
        'content-type':'application/x-www-form-urlencoded'
      },
      data:{
        'openid':test.data.openid,   //用户的opend
        'description':'0.38mm.pen',   //商品描述,此处为简单写了个例子,根据需要进行更改
        'total':1    //商品总金额,单位为分,根据需求可以进行乘100
      },
      success(res){
        console.log(res)
      }
    })
  }

PS:这些JS代码通过点击按钮进行触发的,再次重申,本篇文章仅仅只是介绍获取prepay_id的流程,以及本人在写代码过程中遇到的一些问题
PHP代码:

API_connect.php

<?php
require_once dirname(__DIR__) .'/getCurl/curlDock.php';

class v2Connect
{
    /**
     * @param $URL :访问的API接口地址
     * @param $data :通过POST传递的数据,xml格式
     * @return bool|string :返回数据
     */
    public function connect($URL,$data)
    {
        $this->action = curl_init();
        curl_setopt($this->action, CURLOPT_URL, $URL);
        curl_setopt($this->action, CURLOPT_HEADER, 0);
        //curl_setopt($this->action, CURLOPT_HTTPHEADER, 0);
        curl_setopt($this->action, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($this->action, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($this->action, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->action, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($this->action, CURLOPT_POST, 1);
        curl_setopt($this->action, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($this->action);
        curl_close($this->action);
        return $result;
    }

    /**
     * @return string :返回随机字符串32位
     */
    public function nonce_str(): string
    {
        $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $disposeData = str_shuffle($data);
        return substr($disposeData,0, 32);
    }

    /**
     * @return string :返回商户订单号,非微信官方订单号
     */
    public function out_trade_no(): string
    {
        $data = '1234567890';
        $disposeData = str_shuffle($data);
        $getData = substr($disposeData,5);
        return date('Ymd').time().$getData;
    }

    /**
     * @param $body :商品描述,与$description相同
     * @param $nonce_str :随机字符串32位
     * @param $openid :微信小程序用户身份唯一标识符
     * @param $out_trade_no :商品订单号,商家自行获取,并非微信官方订单号
     * @param $total_fee :订单总金额
     * @return string :返回签名,用于微信预支付订单
     */
    public function getSign ($body,$nonce_str,$openid,$out_trade_no,$total_fee): string
    {
        $data = 'appid=wx9c2877c657b56ed9&body='.$body.'&mch_id=1528263341&nonce_str='.$nonce_str."&".'notify_url=http://001.chutest.xyz/index.php&openid='.$openid.'&out_trade_no='.$out_trade_no.'&spbill_create_ip=127.0.0.1&total_fee='.$total_fee.'&trade_type=JSAPI&key=dv0p6271okvpcawwbin61ht3ds8y6vs7';
        $sign = strtoupper(MD5($data));
        return $sign;
    }

    /**
     * @param $nonce_str :随机字符串32位
     * @param $sign  :签名,用于微信预支付订单
     * @param $description :商品描述
     * @param $openid :微信小程序用户身份唯一标识符
     * @param $out_trade_no :商品订单号,此为商户自行获取,并非微信官方订单号
     * @param $total :订单总金额
     * @throws DOMException
     */
    public function request_body($nonce_str,$sign,$description,$openid,$out_trade_no,$total)
    {
        $getConfig = new curlConnect;

        $request_data = new DOMDocument();
        $request_data -> formatOutput = true;

        $xml = $request_data -> createElement('xml');
        $appid = $request_data -> createElement('appid',$getConfig -> appid);
        $mch_id = $request_data -> createElement('mch_id',$getConfig -> mchID);
        $nonce_str = $request_data -> createElement('nonce_str',$nonce_str);
        $sign = $request_data -> createElement('sign',$sign);
        //$signType = $request_data -> createElement('sign_type','MD5');
        $description = $request_data -> createElement('body',$description);
        $openid = $request_data -> createElement('openid',$openid);
        $out_trade_no = $request_data -> createElement('out_trade_no',$out_trade_no);
        $total_fee = $request_data -> createElement('total_fee',$total);
        $spbill_creat_ip = $request_data -> createElement('spbill_create_ip','127.0.0.1');
        $notify_url = $request_data -> createElement('notify_url','http://001.chutest.xyz/index.php');
        $trade_type = $request_data -> createElement('trade_type','JSAPI');

        $request_data -> appendChild($xml);
        $xml -> appendChild($appid);
        $xml -> appendChild($mch_id);
        $xml -> appendChild($nonce_str);
        $xml -> appendChild($sign);
        //$xml -> appendChild($signType);
        $xml -> appendChild($description);
        $xml -> appendChild($openid);
        $xml -> appendChild($out_trade_no);
        $xml -> appendChild($total_fee);
        $xml -> appendChild($spbill_creat_ip);
        $xml -> appendChild($notify_url);
        $xml -> appendChild($trade_type);

        $request_data -> save('./xmlTest.xml');  //此处可以在同级目录下新建一个xmlTest.xml的文件用来看一下最后生成xml数据的样子
    }
}

PS:注意以上PHP代码中,request_body这一方法中的appid中的 i 是小写字母,若是将其写成大写字母 I 则会在之后的获取微信返回数据验证签名失败

下面是获取prepay_id处理微信返回数据的代码
getPrepay_id.php

<?php
require_once('./API_Connect.php');

$openid = $_POST['openid'];
$body = $_POST['description'];
$total = $_POST['total'];
//$orderName = $_GET['orderName'];
$description = $body;
$total_fee = $total;

//echo $openid;

$getData = new v2Connect;

$nonce_str = $getData->nonce_str();    //获取随机字符串


$out_trade_no = $getData->out_trade_no();  //获取商家订单号


$sign = $getData->getSign($body, $nonce_str, $openid, $out_trade_no, $total_fee);  //获取签名值


$getData->request_body($nonce_str, $sign, $description, $openid, $out_trade_no, $total);  //获取请求数据的主体


$data = file_get_contents('./xmlTest.xml');  //将主体内容存入变量
$URL = 'https://api.mch.weixin.qq.com/pay/unifiedorder';  //发起预支付的请求地址
$result = $getData->connect($URL, $data);   //接收预支付的prepay_id参数
file_put_contents('./result.xml', $result);   //将返回的数据存入文本


$preData = file_get_contents('./result.xml');
$getPrepay = simplexml_load_string($preData);
$prepay_id = $getPrepay -> prepay_id;
echo $prepay_id;

以上代码就完成了获取prepay_id的过程

下面展示一下request_body生成的xml格式数据
xmlTest.xml

<?xml version="1.0"?>
<xml>
  <appid>为了隐私,此处显示你的小程序的appid</appid>
  <mch_id>为了隐私,此处显示你的微信支付商户号</mch_id>
  <nonce_str>3KAERHLXTZBQ74VGO6YMJD2N01IUP5S9</nonce_str>
  <sign>D178D6F5E3B841F976062E320217E04F</sign>
  <body>0.38mm.pen</body>
  <openid>为了隐私,此处我删掉了,此处显示获取到的用户的openid</openid>
  <out_trade_no>20220721165837390737469</out_trade_no>
  <total_fee>1</total_fee>
  <spbill_create_ip>127.0.0.1</spbill_create_ip>
  <notify_url>为了隐私,此处我删掉了,显示的是你的nitify_url微信订单通知的回调地址</notify_url>
  <trade_type>JSAPI</trade_type>
</xml>

下面展示一下,微信返回的包含prepay_id的xml数据

<xml><return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<result_code><![CDATA[SUCCESS]]></result_code>
<mch_id><![CDATA[此处显示你的商户号]]></mch_id>
<appid><![CDATA[此处显示你的appid]]></appid>
<nonce_str><![CDATA[TU7vv4aOH2sJdxkj]]></nonce_str>
<sign><![CDATA[11A449D5E16CEB2B0423AE1EC6503E11]]></sign>
<prepay_id><![CDATA[返回的prepay_id]]></prepay_id>
<trade_type><![CDATA[JSAPI]]></trade_type>
</xml>

总之以上就是小程序微信支付获取prepay_id的流程,还是更推荐大家去仔细看一下微信支付开发者文档,里面写的流程还是很全面的,本篇文章仅供大家参考,文章有纰漏之处,欢迎指正.


本篇文章原创为CSDN用户:缱绻淡蓝海

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值