技术 · 思考 · 实践 · 成长

首页/支付/正文

微信支付 V3 系列(二):Native 支付——统一下单、二维码与异步回调

支付5 次阅读

Native 支付 = 商户后台展示二维码、用户微信扫一扫付款,是 PC 网页收银台的标配。本文把下单 → 二维码 → 轮询/回调 → 关单全流程写透(公共封装见系列一)。

一、支付流程

1. 用户在 PC 网页下单 → 后端创建本地订单(status=0)
2. 调 Native 下单接口 → 返回 code_url
3. 前端把 code_url 渲染成二维码
4. 用户微信扫码 → 输密码支付
5. 微信异步通知 notify_url → 验签/解密 → 订单改 status=1
6. 前端轮询订单状态 → 显示支付成功
(可选)超时未付 → 调关单接口

二、Native 下单接口

POST https://api.mch.weixin.qq.com/v3/pay/transactions/native
{
  "mchid": "1600000000",
  "description": "VIP年费会员",
  "out_trade_no": "ORD20261201000001",
  "notify_url": "https://shop.example.com/pay/notify",
  "amount": { "total": 19800, "currency": "CNY" }
}

应答 { "code_url": "weixin://wxpay/bizpayurl?pr=xxxxx" } —— 这就是二维码内容。

三、ThinkPHP 8 下单实现

<?php
namespace appservice;

use thinkfacadeDb;

class NativePayService extends WxPayService
{
    const PAY_TYPE = 10;      // 与 pay_order.pay_type 约定一致

    public function createOrder(int $userId, string $desc, int $totalFee): array
    {
        $outTradeNo = 'ORD' . date('YmdHis') . mt_rand(1000, 9999);

        // 1. 落库(待支付)
        Db::name('pay_order')->insert([
            'out_trade_no' => $outTradeNo,
            'pay_type'     => self::PAY_TYPE,
            'description'  => $desc,
            'total_fee'    => $totalFee,
            'status'       => 0,
            'create_time'  => date('Y-m-d H:i:s'),
        ]);

        // 2. 调微信下单
        $resp = $this->request('POST', 'https://api.mch.weixin.qq.com/v3/pay/transactions/native', [
            'mchid'        => config('pay.mchid'),
            'description'  => $desc,
            'out_trade_no' => $outTradeNo,
            'notify_url'   => 'https://shop.example.com/pay/notify',
            'amount'       => ['total' => $totalFee, 'currency' => 'CNY'],
        ]);

        return ['out_trade_no' => $outTradeNo, 'code_url' => $resp['code_url']];
    }
}

四、前端:二维码与状态轮询

<div id="qrcode"></div>
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
// 1. 生成二维码
new QRCode(document.getElementById("qrcode"), {
    text: "weixin://wxpay/bizpayurl?pr=xxxxx",   // 后端返回的 code_url
    width: 220, height: 220
});

// 2. 轮询订单状态(每 3 秒)
var timer = setInterval(function () {
    fetch("/pay/status?out_trade_no=ORD20261201000001")
        .then(r => r.json())
        .then(res => {
            if (res.status === 1) {
                clearInterval(timer);
                location.href = "/pay/success";      // 跳成功页
            }
        });
}, 3000);
</script>

后端 /pay/status 只查本地订单状态(状态由回调更新),不要每次轮询都请求微信。

五、异步回调处理(关键)

public function notify()
{
    $headers = request()->header();
    $body    = file_get_contents('php://input');
    $svc     = new WxPayService();

    if (! $svc->verifyNotify($headers, $body, $platformCertPem)) {
        return json(['code' => 'FAIL', 'message' => '验签失败'], 401);
    }

    $data = $svc->decryptResource(json_decode($body, true)['resource']);
    // $data 含 out_trade_no、transaction_id、trade_state、amount 等

    Db::transaction(function () use ($data) {
        $order = Db::name('pay_order')
            ->where('out_trade_no', $data['out_trade_no'])
            ->lock(true)->find();

        if (! $order || $order['status'] == 1) {
            return;                       // 幂等:已处理直接返回成功
        }
        // 核对金额
        if ((int) $data['amount']['total'] !== (int) $order['total_fee']) {
            return;                       // 金额不符,记日志人工介入
        }

        Db::name('pay_order')->where('id', $order['id'])->update([
            'status'        => 1,
            'transaction_id' => $data['transaction_id'],
            'pay_time'      => date('Y-m-d H:i:s'),
            'notify_data'   => json_encode($data, JSON_UNESCAPED_UNICODE),
        ]);
        // 这里触发发货/开通会员等业务
    });

    return json(['code' => 'SUCCESS', 'message' => '成功']);
}

三要点:验签 → 核金额 → 幂等(lock + 状态判断);处理完必须应答 SUCCESS,否则微信会按 15s/15s/30s/3m... 重试多次。

六、查询与关闭订单

// 查询(对账/兜底用)
$this->request('GET', "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{$outTradeNo}?mchid=" . config('pay.mchid'));

// 关闭(超时未支付)
$this->request('POST', "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{$outTradeNo}/close",
    ['mchid' => config('pay.mchid')]);

轮询 N 次仍待支付时调关单,防止用户付到已取消的订单(关单后支付会原路退款)。

七、小案例:完整下单控制器

<?php
namespace appcontroller;

use appserviceNativePayService;
use thinkfacadeDb;

class NativePay
{
    // POST /native/create
    public function create()
    {
        $desc  = input('post.desc/d', '商品');
        $total = input('post.total/d', 0);
        if ($total <= 0) {
            return json(['code' => 0, 'msg' => '金额无效']);
        }
        $res = (new NativePayService())->createOrder(1, $desc, $total);
        return json(['code' => 1, 'data' => $res]);
    }

    // GET /native/status
    public function status()
    {
        $row = Db::name('pay_order')
            ->where('out_trade_no', input('get.out_trade_no'))
            ->field('status')->find();
        return json(['status' => $row['status'] ?? -1]);
    }
}

八、总结

Native 五步:本地下单 → POST /v3/pay/transactions/native 拿 code_url → 前端出码 → 回调改状态(验签/核金额/幂等)→ 轮询跳成功页;金额分、out_trade_no 唯一、回调必须应答 SUCCESS;超时用关单接口兜底。

知识是抵御一切灾祸的盾牌

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读