H5 支付(MWEB)用于手机外部浏览器(Chrome、Safari、UC 等)里的网页支付:下单拿到 h5_url,跳转后拉起微信收银台。流程与 Native 类似但多了场景信息和回跳处理(基础封装见系列一)。
一、支付流程
1. 用户手机浏览器下单 → 后端创建本地订单(status=0)
2. 调 H5 下单接口(带 scene_info)→ 返回 h5_url
3. 前端跳转 h5_url → 拉起微信收银台
4. 用户在微信里完成支付
5. 用户点"完成"返回浏览器 → 提示查询订单
6. 异步通知 → 验签/解密 → 订单改已支付(最终依据)
二、H5 下单接口
POST https://api.mch.weixin.qq.com/v3/pay/transactions/h5
{
"appid": "wx8888888888888888",
"mchid": "1600000000",
"description": "VIP年费会员",
"out_trade_no": "ORD20261201000003",
"notify_url": "https://shop.example.com/pay/notify",
"amount": { "total": 19800, "currency": "CNY" },
"scene_info": {
"payer_client_ip": "113.88.2.1",
"h5_info": { "type": "Wap" }
}
}
应答 { "h5_url": "https://wx.tenpay.com/..." } —— 前端 location.href = h5_url 即可拉起。
三、ThinkPHP 8 下单实现
<?php
namespace appservice;
use thinkfacadeDb;
class H5PayService extends WxPayService
{
const PAY_TYPE = 30;
public function createOrder(int $userId, string $desc, int $totalFee): array
{
$outTradeNo = 'ORD' . date('YmdHis') . mt_rand(1000, 9999);
Db::name('pay_order')->insert([
'out_trade_no' => $outTradeNo,
'pay_type' => self::PAY_TYPE,
'description' => $desc,
'total_fee' => $totalFee,
'status' => 0,
]);
$resp = $this->request('POST', 'https://api.mch.weixin.qq.com/v3/pay/transactions/h5', [
'appid' => config('pay.appid'),
'mchid' => config('pay.mchid'),
'description' => $desc,
'out_trade_no' => $outTradeNo,
'notify_url' => 'https://shop.example.com/pay/notify',
'amount' => ['total' => $totalFee, 'currency' => 'CNY'],
'scene_info' => [
'payer_client_ip' => request()->ip(),
'h5_info' => ['type' => 'Wap'],
],
]);
return ['out_trade_no' => $outTradeNo, 'h5_url' => $resp['h5_url']];
}
}
四、回跳与结果展示
- 用户在微信支付完成,点"完成"才回到浏览器 —— 回跳不可靠,不能只靠它
- 推荐:跳转前记住订单号,回到结果页后轮询订单状态(同系列二的 status 接口)
- h5_url 有时效(约 5 分钟),过期需重新下单
// 结果页轮询
var timer = setInterval(function () {
fetch("/pay/status?out_trade_no=ORD20261201000003")
.then(r => r.json())
.then(res => {
if (res.status === 1) { clearInterval(timer); location.href = "/pay/success"; }
});
}, 3000);
五、注意事项
| 事项 | 说明 |
|---|---|
| 产品开通 | 商户平台需单独开通 H5 支付并配置支付域名(referer 域名) |
| refer 校验 | 下单请求来源域名需与配置一致,否则报错 |
| payer_client_ip | 用户真实出口 IP,别写服务器 IP |
| 金额 | 单位分;与订单表核对(回调三要点见系列二) |
| HTTPS | notify_url 与页面均需 HTTPS |
六、小案例:完整下单控制器
<?php
namespace appcontroller;
use appserviceH5PayService;
class H5Pay
{
// POST /h5/create
public function create()
{
$total = input('post.total/d', 0);
if ($total <= 0) {
return json(['code' => 0, 'msg' => '金额无效']);
}
try {
$res = (new H5PayService())->createOrder(1, 'VIP年费会员', $total);
} catch (Throwable $e) {
hinkfacadeLog::warning('H5下单失败:' . $e->getMessage());
return json(['code' => 0, 'msg' => '下单失败,请稍后重试']);
}
return json(['code' => 1, 'h5_url' => $res['h5_url'], 'order_no' => $res['out_trade_no']]);
}
}
七、总结
H5 支付 = 下单(带 scene_info:客户端 IP + Wap)→ h5_url 跳转拉起 → 回跳不可靠、轮询为准;开通需配置支付域名;回调三要点照旧,金额用分。