返回

用原生PHP对接微信小程序支付过程分析

后端

准备工作

1. 开发环境准备

  • 安装PHP扩展库
sudo apt-get install php-curl
  • 开启PHP错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

2. 微信支付配置

  • 注册微信支付商户号

  • 获取微信支付密钥

  • 配置微信支付参数

$appid = 'wx1234567890123456';
$mch_id = '1234567890';
$api_key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

微信小程序支付流程

1. 统一下单

$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

$data = [
    'appid' => $appid,
    'mch_id' => $mch_id,
    'nonce_str' => md5(uniqid()),
    'body' => '商品名称',
    'out_trade_no' => '订单号',
    'total_fee' => 1,
    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
    'notify_url' => '回调地址',
    'trade_type' => 'JSAPI',
    'openid' => '用户的OpenID',
];

$sign = md5(urldecode(http_build_query($data)) . '&key=' . $api_key);
$data['sign'] = $sign;

$xml = simplexml_load_string(curl_post($url, $data));

if ($xml->return_code == 'SUCCESS') {
    // 成功统一下单

    $prepay_id = $xml->prepay_id;
} else {
    // 统一下单失败
}

2. 生成支付参数

$timestamp = time();
$nonce_str = md5(uniqid());

$data = [
    'appId' => $appid,
    'timeStamp' => $timestamp,
    'nonceStr' => $nonce_str,
    'package' => 'prepay_id=' . $prepay_id,
    'signType' => 'MD5',
];

$sign = md5(urldecode(http_build_query($data)) . '&key=' . $api_key);
$data['paySign'] = $sign;

$json = json_encode($data);

3. 发起支付

wx.requestPluginPayment({
    pluginAppId: 'wx1234567890123456',
    plugin: 'qwallet',
    payInfo: $json,
    success: function(res) {
        // 支付成功
    },
    fail: function(res) {
        // 支付失败
    }
});

4. 支付回调

$data = file_get_contents('php://input');

if (empty($data)) {
    // 回调数据为空
}

$xml = simplexml_load_string($data);

if ($xml->return_code == 'SUCCESS' && $xml->result_code == 'SUCCESS') {
    // 支付成功

    // 更新订单状态
} else {
    // 支付失败
}

结语

本文详细介绍了使用原生PHP对接微信小程序支付的全过程,包括环境准备、微信支付配置、统一下单、生成支付参数、发起支付和支付回调。希望对您有所帮助。