改善支付体验:从浏览器跳转到国内支付应用
引言
接入支付是许多 SaaS 应用的重要环节。本文讨论怎样改善使用支付宝和微信支付时的用户支付体验,重点是对海外用户影响很大的浏览器跳转问题。
为什么浏览器跳转值得关注?
为国内支付平台实现扫码付款时,开发者常会遇到一个影响中国大陆以外用户的体验问题。
用户在哪一步卡住?
传统扫码付款流程
- 应用显示付款二维码。
- 用户用手机相机扫码。
- 问题:系统相机在默认浏览器(Safari、Chrome 等)中打开付款网址。
- 用户看得到付款页面,却无法在该页面完成付款。
- 用户得手工复制链接,转到支付宝或微信中打开。
原因
-
中国大陆的用户通常用支付宝或微信应用内的扫一扫。
- 扫码后付款页面会在应用内部打开。
- 全程无需切换到系统浏览器。
-
海外用户较常用手机自带相机扫码。
- 相机默认用系统浏览器打开网址。
- 浏览器不能直接调用应用内部的支付能力。
- 因此付款流程可能中断。
对用户体验的影响
❌ Poor UX (Default Behavior):
User scans QR → Opens in Browser → Stuck → Must manually open in app (5+ steps)
Conversion rate: ~40-60% (many users give up)
✅ Enhanced UX (Browser-to-App Jump):
User scans QR → Opens in Browser → Auto-jumps to App → Completes payment (2 steps)
Conversion rate: ~85-95% (seamless experience)
实际使用场景
设想一个 SaaS 产品面向下列用户:
- 香港、台湾、新加坡的用户:手机装了支付宝或微信,却用系统相机扫码。
- 留学生或海外工作者:使用中国支付应用,但不熟悉应用内扫码。
- 商旅人士:只想尽快完成一笔交易,无暇了解各应用的操作习惯。
对这些用户而言,能否从浏览器顺利进入支付应用,会直接影响交易能不能完成。
目标:让支付流程连贯
本文关注以下问题:
- 理解支付宝、微信支付从浏览器进入应用的机制。
- 在适用时使用 URL scheme(支付宝)。
- 按平台约束选择路径(微信支付)。
- 借助富友支付等聚合服务简化接入。
- 改善付款流程,减少用户需要额外操作的步骤。
这些方法面向用手机相机扫码的人,希望通过减少中断提高付款转化率。
支付宝接入
概况
支付宝是国内广泛使用的移动支付平台。严格的商户要求可能使个人开发者或小企业难以直接接入官方 SDK。其他选择包括第三方聚合支付服务(有时称“四方支付”),或者在移动端用 scheme 打开付款页面。
难点
在本文讨论的接入条件下,个人开发者无法直接开通带 webhook 的支付服务,通常得考虑:
- 使用聚合支付服务。
- 在移动应用中采用适配的跳转方案。
移动端通过 URI scheme 接入
对 Android 或 iOS 应用,可以用支付宝的 URI scheme 直接在支付宝里打开付款页面,省去完整 SDK 接入的部分工作。
工作原理
扫描支付宝二维码,本质上是在支付宝内置浏览器里打开 H5 付款链接。如果应用能让支付宝打开该链接,用户同样可以进入付款环节。
第一步:认识支付宝 URI scheme
外部应用可以调用支付宝提供的自定义 URI scheme:
alipays://platformapi/startapp?appId=20000067&url=<PAYMENT_URL>
参数
appId=20000067:支付宝内部浏览器或付款模块的应用 ID。url=<PAYMENT_URL>:H5 付款网址,需要先做 URL 编码。
第二步:Android 实现
下面是使用 Kotlin 的 Android 示例:
import android.content.Intent
import android.net.Uri
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import java.net.URLEncoder
fun openAlipayPayment(payUrl: String) {
// Check if Alipay is installed
if (AppUtils.isAppInstalled("com.eg.android.AlipayGphone")) {
// URL-encode the payment URL
val encodedUrl = URLEncoder.encode(payUrl, "UTF-8")
val scheme = "alipays://platformapi/startapp?appId=20000067&url=$encodedUrl"
// Create intent and launch Alipay
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(scheme))
ActivityUtils.startActivity(intent)
} else {
ToastUtils.showShort("Alipay app is not installed on this device")
}
}
要点
- 打开前先检查是否安装了支付宝。
- 对付款网址做 URL 编码,避免解析错误。
- 用
Intent.ACTION_VIEW处理自定义 URI scheme。 - 支付宝的包名是
com.eg.android.AlipayGphone。
第三步:iOS 实现
在使用 Swift 的 iOS 应用中:
import UIKit
func openAlipayPayment(payUrl: String) {
guard let encodedUrl = payUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
print("Failed to encode URL")
return
}
let scheme = "alipays://platformapi/startapp?appId=20000067&url=\(encodedUrl)"
if let url = URL(string: scheme) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:]) { success in
if !success {
print("Failed to open Alipay")
}
}
} else {
// Show alert that Alipay is not installed
showAlert(message: "Alipay app is not installed on this device")
}
}
}
func showAlert(message: String) {
let alert = UIAlertController(title: "Notice", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
if let topController = UIApplication.shared.keyWindow?.rootViewController {
topController.present(alert, animated: true)
}
}
iOS 配置
还需要在 Info.plist 中添加支付宝 URL scheme:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>alipays</string>
<string>alipay</string>
</array>
第四步:网页和桌面端实现
网页或桌面软件通常生成二维码。
网页跳转注意事项
在网页里通过 URL scheme 打开应用时,建议使用 <a> 链接,而非在 <button> 的 onClick 中模拟跳转,原因如下:
- 可以使用浏览器自身的 URL 处理机制,兼容性较好。
- 移动设备切换应用时更符合原生行为。
- 减少事件冒泡和 preventDefault 带来的干扰。
- 在 iOS 和 Android 浏览器中更容易保持一致。
// ✅ RECOMMENDED: Use anchor tag
<a
href="alipays://platformapi/startapp?appId=20000067&url=encoded_url"
className="button-styles"
>
Open Alipay
</a>
// ❌ AVOID: Button with onClick handler
<button onClick={()=> window.location.href= "alipays://..."}>
Open Alipay
</button>
// Generate QR code for payment URL
import QRCode from 'qrcode';
async function generateAlipayQRCode(paymentUrl) {
try {
const qrCodeDataUrl = await QRCode.toDataURL(paymentUrl, {
width: 300,
margin: 2,
color: {
dark: '#1677FF', // Alipay blue
light: '#FFFFFF'
}
});
return qrCodeDataUrl;
} catch (error) {
console.error('Failed to generate QR code:', error);
throw error;
}
}
// Usage
const paymentUrl = "https://your-payment-gateway.com/pay?order_id=123456";
const qrCodeImage = await generateAlipayQRCode(paymentUrl);
// Display QR code to user
document.getElementById('qr-code-container').innerHTML =
`<img src="${qrCodeImage}" alt="Scan to pay with Alipay" />`;
后端与支付网关的对接
使用聚合支付服务时,后端流程通常如下:
// Node.js/Express example
const express = require('express');
const axios = require('axios');
app.post('/api/create-alipay-order', async (req, res) => {
try {
const { amount, orderId, productName } = req.body;
// Call your payment gateway API
const response = await axios.post('https://payment-gateway.com/api/create-order', {
payment_method: 'alipay',
amount: amount,
order_id: orderId,
product_name: productName,
notify_url: 'https://your-domain.com/api/payment-callback',
return_url: 'https://your-domain.com/payment-success'
}, {
headers: {
'Authorization': `Bearer ${process.env.PAYMENT_GATEWAY_API_KEY}`
}
});
// Return the H5 payment URL to client
res.json({
success: true,
payment_url: response.data.h5_url,
order_id: response.data.order_id
});
} catch (error) {
console.error('Failed to create Alipay order:', error);
res.status(500).json({
success: false,
error: 'Failed to create payment order'
});
}
});
// Payment callback endpoint
app.post('/api/payment-callback', async (req, res) => {
try {
const { order_id, status, signature } = req.body;
// Verify signature (important for security)
if (!verifySignature(req.body, signature)) {
return res.status(400).send('Invalid signature');
}
// Update order status in database
await updateOrderStatus(order_id, status);
// Send confirmation to payment gateway
res.send('success');
} catch (error) {
console.error('Payment callback error:', error);
res.status(500).send('error');
}
});
安全事项
- 校验 webhook:验证支付回调签名,防止伪造。
- 使用 HTTPS:所有支付相关端点都应使用 HTTPS。
- 校验输入:验证并处理用户输入。
- 安全保存凭据:API 密钥通过环境变量等方式提供,避免写进源码。
- 保持幂等:同一笔付款不能重复处理。
- 限制请求频率:保护支付端点免遭滥用。
测试
开发测试时可用:
- 沙箱环境:多数支付网关提供沙箱凭据。
- 支付宝测试账户:开发阶段可使用测试账号。
- 模拟 webhook:用 ngrok 等工具将测试回调送到本地。
# Example: Using ngrok to expose local server for webhook testing
ngrok http 3000
# Update your payment gateway's notify_url to the ngrok URL
# https://your-ngrok-url.ngrok.io/api/payment-callback
常见问题与解决办法
问题一:支付宝没有打开
- 检查 URL 是否正确编码,scheme 是否正确。
- 检查用户是否安装支付宝。
问题二:未收到支付回调
- 确认回调网址能从公网访问(不能只是 localhost)。
- 检查防火墙和安全组设置。
- 检查测试回调是否被验签逻辑误拒。
问题三:一笔付款被处理两次
- 使用幂等键。
- 处理回调前检查订单状态。
async function handlePaymentCallback(orderId, newStatus) {
// Use database transaction for atomic operations
const order = await db.transaction(async (trx) => {
const order = await trx('orders')
.where({ id: orderId })
.first();
// Prevent duplicate processing
if (order.status === 'paid') {
console.log('Order already processed:', orderId);
return order;
}
// Update order status
await trx('orders')
.where({ id: orderId })
.update({
status: newStatus,
paid_at: new Date()
});
return order;
});
return order;
}
实践建议
-
用户体验
- 展示清晰的支付说明。
- 初始化支付时显示加载状态。
- 超时后给出清楚的处理方式。
-
错误处理
- 提供有意义的报错。
- 记录支付相关错误供排查。
- 为失败的交易设计重试机制。
-
监控
- 跟踪付款成功率。
- 监控 webhook 送达率。
- 为付款失败设置告警。
-
合规
- 处理银行卡数据时遵循 PCI DSS 要求。
- 遵守当地支付法规。
- 保留各笔交易的审计日志。
微信支付接入
概况
微信支付集成在微信中,同样是国内主要支付平台。和支付宝相比,本文尝试的外部应用调用和 URL scheme 路径受到较严格的限制,增加了第三方应用接入的难度。
核心限制:普通浏览器不能直接调用微信内的支付桥
注意: 本文讨论的普通网页或外部应用不能靠自定义 URL scheme 或 JavaScript 桥直接跳入微信触发这类支付。这与腾讯对安全和用户体验的设计有关。
几种没有奏效的尝试
很多开发者都会想到以下做法,但它们解决不了这个场景。
❌ 方法一:在微信外使用 WeixinJSBridge
有些教程建议用 WeixinJSBridge 打开链接:
// ❌ THIS DOES NOT WORK outside WeChat's built-in browser
function openWechatLink(url) {
if(typeof WeixinJSBridge == "undefined") {
if(document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', function() {
openLink(url);
}, false);
} else if(document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', function() {
openLink(url);
});
document.attachEvent('onWeixinJSBridgeReady', function() {
openLink(url);
});
}
} else {
openLink(url);
}
}
function openLink(url) {
WeixinJSBridge.invoke('openUrl', {
"url": url,
"delay": 0
});
}
// This will NOT work in external browsers
openWechatLink('http://www.example.com');
失败原因
WeixinJSBridge只存在于微信内置浏览器环境。- 它是微信小程序及应用内 WebView 等场景使用的接口。
- 外部网页和应用访问不到它。
- 官方文档也说明了适用环境。
❌ 方法二:使用适用范围有限的微信 JSSDK
也有人尝试微信 JSSDK:
// ❌ THIS ALSO DOESN'T WORK for what you think
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
// Many tutorials mention this, but...
wx.openUrlWithExtraWebview({
// This function DOESN'T EXIST in the SDK source code!
url: 'payment-url'
});
失败原因
- JSSDK 没有
wx.openUrlWithExtraWebview()这个函数。 - JSSDK 主要提供分享、定位、扫码等能力。
- 外部应用无法靠它直接发起付款。
- 其中的支付接口只在相应的微信环境中生效。
❌ 方法三:自定义 URL scheme
与前述支付宝案例不同,试图用以下自定义 scheme 打开微信没有奏效:
// ❌ WeChat has blocked this type of invocation
const wechatScheme = "weixin://dl/business/?t=payment_url";
window.location.href = wechatScheme; // Won't work
失败原因
- 微信限制通过此类 URL scheme 拉起应用。
- 其中也有安全、防钓鱼方面的考虑。
- 拉起能力受特定场景和授权范围限制。
可用的官方接入方法
在这些约束下,可以考虑以下微信支付接入方式:
方法一:二维码支付(桌面和网页常用)
网页和桌面软件的标准流程如下。
流程
- 用户在网站或应用中发起付款。
- 后端创建微信支付订单,取得二维码 URL。
- 向用户展示二维码。
- 用户用微信扫码。
- 用户在微信里完成支付。
- webhook 通知确认付款结果。
后端实现(Node.js)
const axios = require('axios');
const crypto = require('crypto');
async function createWeChatPayOrder(orderData) {
const {
amount, // Amount in cents (e.g., 100 = ¥1.00)
orderId,
description,
notifyUrl
} = orderData;
// WeChat Pay API endpoint
const apiUrl = 'https://api.mch.weixin.qq.com/v3/pay/transactions/native';
// Prepare request body
const requestBody = {
appid: process.env.WECHAT_APP_ID,
mchid: process.env.WECHAT_MERCHANT_ID,
description: description,
out_trade_no: orderId,
notify_url: notifyUrl,
amount: {
total: amount,
currency: 'CNY'
}
};
try {
// Sign request with merchant certificate
const signature = signRequest(requestBody);
const response = await axios.post(apiUrl, requestBody, {
headers: {
'Content-Type': 'application/json',
'Authorization': signature
}
});
// Response contains code_url for QR code generation
return {
success: true,
qr_code_url: response.data.code_url,
order_id: orderId
};
} catch (error) {
console.error('WeChat Pay order creation failed:', error);
throw error;
}
}
// Sign request according to WeChat Pay requirements
function signRequest(body) {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString('hex');
// Construct signature string
const signatureStr = `POST\n/v3/pay/transactions/native\n${timestamp}\n${nonce}\n${JSON.stringify(body)}\n`;
// Sign with merchant private key
const sign = crypto
.createSign('RSA-SHA256')
.update(signatureStr)
.sign(process.env.WECHAT_MERCHANT_KEY, 'base64');
return `WECHATPAY2-SHA256-RSA2048 mchid="${process.env.WECHAT_MERCHANT_ID}",nonce_str="${nonce}",signature="${sign}",timestamp="${timestamp}",serial_no="${process.env.WECHAT_CERT_SERIAL}"`;
}
前端实现
import QRCode from 'qrcode';
async function displayWeChatPayQRCode(orderId, amount) {
try {
// Request order creation from backend
const response = await fetch('/api/create-wechat-order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
order_id: orderId,
amount: amount,
description: 'Product purchase'
})
});
const data = await response.json();
// Generate QR code from code_url
const qrCodeDataUrl = await QRCode.toDataURL(data.qr_code_url, {
width: 300,
margin: 2,
color: {
dark: '#09BB07', // WeChat green
light: '#FFFFFF'
}
});
// Display QR code
document.getElementById('wechat-qr-container').innerHTML = `
<div class="payment-qr-box">
<img src="${qrCodeDataUrl}" alt="Scan to pay with WeChat" />
<p>Open WeChat and scan to pay</p>
<p class="amount">¥${(amount / 100).toFixed(2)}</p>
</div>
`;
// Poll for payment status
pollPaymentStatus(orderId);
} catch (error) {
console.error('Failed to create WeChat Pay order:', error);
}
}
// Poll backend to check if payment is completed
function pollPaymentStatus(orderId) {
const pollInterval = setInterval(async () => {
const response = await fetch(`/api/check-order-status/${orderId}`);
const data = await response.json();
if (data.status === 'paid') {
clearInterval(pollInterval);
showPaymentSuccess();
} else if (data.status === 'expired') {
clearInterval(pollInterval);
showPaymentExpired();
}
}, 2000); // Check every 2 seconds
// Stop polling after 5 minutes
setTimeout(() => clearInterval(pollInterval), 300000);
}
方法二:原生应用接入(需要官方 SDK)
原生移动应用按官方 SDK 的约定接入:
Android(Kotlin)
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
class WeChatPayment(private val context: Context) {
private var wxApi: IWXAPI? = null
init {
// Initialize WeChat SDK
wxApi = WXAPIFactory.createWXAPI(context, WECHAT_APP_ID, true)
wxApi?.registerApp(WECHAT_APP_ID)
}
fun launchWeChatPay(paymentData: PaymentData) {
// Check if WeChat is installed
if (wxApi?.isWXAppInstalled == false) {
Toast.makeText(context, "WeChat is not installed", Toast.LENGTH_SHORT).show()
return
}
// Create payment request
val request = PayReq().apply {
appId = paymentData.appId
partnerId = paymentData.partnerId
prepayId = paymentData.prepayId
packageValue = paymentData.packageValue
nonceStr = paymentData.nonceStr
timeStamp = paymentData.timeStamp
sign = paymentData.sign
}
// Launch WeChat Pay
wxApi?.sendReq(request)
}
companion object {
private const val WECHAT_APP_ID = "your_wechat_app_id"
}
}
// Data class for payment parameters
data class PaymentData(
val appId: String,
val partnerId: String,
val prepayId: String,
val packageValue: String,
val nonceStr: String,
val timeStamp: String,
val sign: String
)
iOS(Swift)
import WechatOpenSDK
class WeChatPaymentManager: NSObject {
static let shared = WeChatPaymentManager()
func registerApp() {
WXApi.registerApp("your_wechat_app_id", universalLink: "your_universal_link")
}
func launchWeChatPay(paymentData: PaymentData) {
// Check if WeChat is installed
guard WXApi.isWXAppInstalled() else {
print("WeChat is not installed")
return
}
// Create payment request
let request = PayReq()
request.partnerId = paymentData.partnerId
request.prepayId = paymentData.prepayId
request.package = paymentData.package
request.nonceStr = paymentData.nonceStr
request.timeStamp = UInt32(paymentData.timeStamp) ?? 0
request.sign = paymentData.sign
// Send request to WeChat
WXApi.send(request)
}
}
struct PaymentData {
let partnerId: String
let prepayId: String
let package: String
let nonceStr: String
let timeStamp: String
let sign: String
}
方法三:微信内网页支付(JSAPI)
用户已经在微信内置浏览器中时,可以使用 JSAPI 支付:
// This ONLY works inside WeChat's built-in browser
function onBridgeReady(paymentParams) {
WeixinJSBridge.invoke('getBrandWCPayRequest', {
"appId": paymentParams.appId,
"timeStamp": paymentParams.timeStamp,
"nonceStr": paymentParams.nonceStr,
"package": paymentParams.package,
"signType": paymentParams.signType,
"paySign": paymentParams.paySign
}, function(res) {
if(res.err_msg == "get_brand_wcpay_request:ok") {
// Payment successful
window.location.href = '/payment-success';
} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
// User cancelled
alert('Payment cancelled');
} else {
// Payment failed
alert('Payment failed');
}
});
}
// Check if WeixinJSBridge is ready
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', function() {
onBridgeReady(paymentParams);
}, false);
}
} else {
onBridgeReady(paymentParams);
}
处理支付回调
和支付宝一样,也要处理付款回调:
app.post('/api/wechat-payment-callback', async (req, res) => {
try {
const { resource } = req.body;
// Decrypt notification data
const decryptedData = decryptWeChatNotification(resource);
// Verify signature
if (!verifyWeChatSignature(req.headers, req.body)) {
return res.status(400).json({ code: 'FAIL', message: 'Invalid signature' });
}
const { out_trade_no, transaction_id, trade_state } = decryptedData;
if (trade_state === 'SUCCESS') {
// Update order status in database
await updateOrderStatus(out_trade_no, 'paid', transaction_id);
// Return success response
res.json({ code: 'SUCCESS', message: 'OK' });
} else {
res.json({ code: 'FAIL', message: 'Payment not successful' });
}
} catch (error) {
console.error('WeChat payment callback error:', error);
res.status(500).json({ code: 'FAIL', message: 'Internal error' });
}
});
function decryptWeChatNotification(resource) {
const { ciphertext, nonce, associated_data } = resource;
// Decrypt using AES-256-GCM
const decipher = crypto.createDecipheriv(
'aes-256-gcm',
process.env.WECHAT_API_V3_KEY,
nonce
);
decipher.setAuthTag(Buffer.from(resource.additional_data, 'base64'));
decipher.setAAD(Buffer.from(associated_data));
let decrypted = decipher.update(ciphertext, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return JSON.parse(decrypted);
}
微信支付与支付宝的区别
| 能力 | 支付宝 | 微信支付 |
|---|---|---|
| URL scheme | ✅ 可用(alipays://) | ❌ 本文场景受限 |
| 从浏览器进应用 | ✅ 本例可行 | ❌ 本例无法直接调用 |
| 扫码支付 | ✅ 支持 | ✅ 支持 |
| 官方 SDK | 基础接入可选 | 原生移动应用需要 |
| 网页付款 | 较灵活 | 此处的 JSAPI 路径要求微信内置浏览器 |
| 个人开发者接入 | 受限 | 受限 |
| 商户要求 | 严格 | 很严格 |
建议
- 网页或桌面应用:本文优先选用二维码支付。
- 原生应用:接入微信官方 SDK。
- 微信内网页:已在微信里时采用 JSAPI。
- 第三方支付:可借助聚合服务处理部分接入复杂度。
常见误区
- 在普通网页直接调用微信支付桥这条路上反复试探,会浪费时间。
- 不要依赖声称
WeixinJSBridge在微信外也可用的旧教程。 - 不要试图逆向微信的应用启动机制。
- 按照官方接入指南配置。
- 原生移动应用使用官方 SDK。
微信支付小结
相比支付宝较灵活的入口,微信支付明确区分环境。就本文场景而言,应按腾讯的正式渠道实现:
- 网页和桌面使用二维码。
- 原生应用使用官方 SDK。
- 微信内体验使用 JSAPI。
尽管约束较多,这有助于在微信生态内保持安全和一致的体验。
第三方聚合服务:富友支付示例
概况
支付宝和微信支付直接接入都有不少要求,因此许多开发者采用第三方聚合支付服务(有时也称四方支付)。它作为中间层,以统一 API 简化多种支付方式的接入。
富友支付是国内一个例子,既能展示聚合的便利,也能看到它的边界。
富友支付的接入方式
方法一:支付宝用 URL scheme 配合二维码链接(可行 ✅)
富友为支付宝提供一个付款 URL,可配合前面的 scheme 使用:
// Backend: Create Fuyou Pay order for Alipay
async function createFuyouAlipayOrder(orderData) {
const response = await axios.post('https://api.fuyoupay.com/create-order', {
payment_method: 'alipay',
amount: orderData.amount,
order_id: orderData.orderId,
notify_url: 'https://your-domain.com/api/fuyou-callback'
}, {
headers: {
'Authorization': `Bearer ${process.env.FUYOU_API_KEY}`
}
});
// Fuyou returns an h5_url that can be used for both QR code and URL scheme
return {
h5_url: response.data.h5_url,
order_id: response.data.order_id
};
}
// Frontend: Mobile app can use URL scheme
async function payWithFuyouAlipay(orderId, amount) {
// Get payment URL from backend
const { h5_url } = await createFuyouAlipayOrder({ orderId, amount });
// For mobile apps: Use URL scheme to jump to Alipay
if (isMobileApp) {
const scheme = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(h5_url)}`;
window.location.href = scheme;
}
// For web/desktop: Generate QR code
else {
const qrCode = await QRCode.toDataURL(h5_url);
displayQRCode(qrCode);
}
}
能这样工作的原因是:
- 富友提供的是 H5 付款 URL。
- 可通过
alipays://在支付宝内置浏览器中打开。 - 同一网址也能生成二维码供桌面用户扫描。
方法二:微信走 JSAPI(有限制 ⚠️)
富友在这个微信付款场景中提供的是 JSAPI,存在以下限制。
必要条件: 你需要自己的微信公众号或小程序。
// Backend: Create Fuyou WeChat Pay order using JSAPI
async function createFuyouWeChatOrder(orderData) {
const { userId, amount, orderId } = orderData;
// IMPORTANT: You need the user's WeChat OpenID
// This requires users to authorize via your Official Account first
const openId = await getUserWeChatOpenId(userId);
if (!openId) {
throw new Error('User must authorize WeChat Official Account first');
}
const response = await axios.post('https://api.fuyoupay.com/create-order', {
payment_method: 'wechat_jsapi',
amount: amount,
order_id: orderId,
openid: openId, // Required for JSAPI
notify_url: 'https://your-domain.com/api/fuyou-callback'
}, {
headers: {
'Authorization': `Bearer ${process.env.FUYOU_API_KEY}`
}
});
// Fuyou returns JSAPI payment parameters
return {
appId: response.data.appId,
timeStamp: response.data.timeStamp,
nonceStr: response.data.nonceStr,
package: response.data.package,
signType: response.data.signType,
paySign: response.data.paySign
};
}
前端实现(需要微信内置浏览器)
// This ONLY works inside WeChat's built-in browser
async function payWithFuyouWeChat(orderId, amount) {
try {
// Get JSAPI parameters from backend
const paymentParams = await createFuyouWeChatOrder({
userId: currentUserId,
amount: amount,
orderId: orderId
});
// Check if we're in WeChat browser
if (!isWeChatBrowser()) {
alert('Please open this page in WeChat to complete payment');
return;
}
// Invoke WeChat payment using JSAPI
if (typeof WeixinJSBridge === "undefined") {
document.addEventListener('WeixinJSBridgeReady', function() {
invokeFuyouWeChatPay(paymentParams);
}, false);
} else {
invokeFuyouWeChatPay(paymentParams);
}
} catch (error) {
console.error('WeChat payment failed:', error);
alert('Payment initialization failed');
}
}
function invokeFuyouWeChatPay(paymentParams) {
WeixinJSBridge.invoke('getBrandWCPayRequest', {
"appId": paymentParams.appId,
"timeStamp": paymentParams.timeStamp,
"nonceStr": paymentParams.nonceStr,
"package": paymentParams.package,
"signType": paymentParams.signType,
"paySign": paymentParams.paySign
}, function(res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
// Payment successful
window.location.href = '/payment-success?order_id=' + orderId;
} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
alert('Payment cancelled');
} else {
alert('Payment failed: ' + res.err_msg);
}
});
}
// Utility function to detect WeChat browser
function isWeChatBrowser() {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
}
富友微信 JSAPI 的前提
根据与技术支持的沟通,这条接入路径要求:
- 自己的微信公众号或小程序。
- 用户授权:用户授权公众号,使应用取得自己的 OpenID。
- H5 应用:应用可通过移动端网页访问。
- 微信浏览器环境:付款需在微信内发起。
获取用户的微信 OpenID
处理微信付款前,需要用户的 OpenID:
// Step 1: Redirect user to WeChat OAuth page
function redirectToWeChatAuth() {
const appId = process.env.WECHAT_OFFICIAL_ACCOUNT_APP_ID;
const redirectUri = encodeURIComponent('https://your-domain.com/wechat-callback');
const state = generateRandomState(); // CSRF protection
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
window.location.href = authUrl;
}
// Step 2: Handle OAuth callback
app.get('/wechat-callback', async (req, res) => {
const { code, state } = req.query;
// Verify state for CSRF protection
if (!verifyState(state)) {
return res.status(400).send('Invalid state');
}
try {
// Exchange code for access token and OpenID
const tokenResponse = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
params: {
appid: process.env.WECHAT_OFFICIAL_ACCOUNT_APP_ID,
secret: process.env.WECHAT_OFFICIAL_ACCOUNT_SECRET,
code: code,
grant_type: 'authorization_code'
}
});
const { openid, access_token } = tokenResponse.data;
// Store OpenID associated with user account
await saveUserWeChatOpenId(req.session.userId, openid);
// Redirect to payment page
res.redirect('/payment');
} catch (error) {
console.error('WeChat OAuth failed:', error);
res.status(500).send('Authorization failed');
}
});
直接接入与富友支付对比
| 项目 | 直接接入 | 富友支付(聚合) |
|---|---|---|
| 配置复杂度 | 高,两平台分别登记 | 中,一次登记 |
| 支付宝 URL scheme | ✅ 可直接用 | ✅ 通过 H5 链接 |
| 微信 URL scheme | ❌ 不可用 | ❌ 仍不可用 |
| 微信 JSAPI | 需要公众号与商户账号 | ✅ 本例只需自行准备公众号 |
| 二维码付款 | ✅ 两平台均支持 | ✅ 两平台均支持 |
| 交易费用 | 较低,仅直接支付费 | 较高,支付费加聚合服务费 |
| 统一 API | ❌ 各平台分别接入 | ✅ 同一 API |
| 回调处理 | 各平台分别处理 | 统一回调格式 |
聚合方式的限制
-
微信支付的约束仍在
- 不能从外部浏览器或应用直接跳入本文所用微信付款路径。
- 仍需微信浏览器环境。
- 需要公众号,得额外配置。
-
额外成本
- 支付平台费用之外还要支付聚合服务费。
- 文中估计每笔额外成本通常为 0.3%–0.6%。
-
依赖风险
- 依赖第三方服务的可用性。
- 可能出现服务中断。
- 对付款流程的掌控较少。
-
合规要求
- 聚合服务可能有各自的合规条件。
- 部分行业可能要求直接接入。
什么时候适合用富友等聚合服务?
适合聚合的情形
- 需要尽快支持多种付款方式。
- 需要统一处理回调。
- 正在做 MVP,希望尽快上线。
- 交易量中低,可以接受费率。
- 希望通过单一商户账号简化对账。
适合直接接入的情形
- 交易量大,希望节省聚合费用。
- 需要最大限度掌控付款流程。
- 正在构建长期运行的大规模应用。
- 需要聚合服务没有的特性。
- 法规要求直接接入。
完整示例:统一付款处理器
下面的例子通过富友同时处理支付宝和微信付款:
class FuyouPaymentHandler {
async initiatePayment(userId, orderId, amount, method) {
// Create order via Fuyou API
const orderData = await this.createFuyouOrder(userId, orderId, amount, method);
if (method === 'alipay') {
return this.handleAlipayPayment(orderData);
} else if (method === 'wechat') {
return this.handleWeChatPayment(orderData);
}
}
async createFuyouOrder(userId, orderId, amount, method) {
const payload = {
order_id: orderId,
amount: amount,
payment_method: method,
notify_url: 'https://your-domain.com/api/fuyou-callback'
};
// For WeChat, we need OpenID
if (method === 'wechat') {
const openId = await this.getUserOpenId(userId);
if (!openId) {
throw new Error('WECHAT_AUTH_REQUIRED');
}
payload.openid = openId;
}
const response = await axios.post('https://api.fuyoupay.com/create-order', payload, {
headers: { 'Authorization': `Bearer ${process.env.FUYOU_API_KEY}` }
});
return response.data;
}
handleAlipayPayment(orderData) {
const { h5_url } = orderData;
// Detect platform
if (this.isMobileApp()) {
// Mobile app: Use URL scheme
const scheme = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(h5_url)}`;
return {
type: 'url_scheme',
url: scheme
};
} else {
// Web/Desktop: Generate QR code
return {
type: 'qr_code',
url: h5_url
};
}
}
handleWeChatPayment(orderData) {
// WeChat can only work with JSAPI in WeChat browser
if (!this.isWeChatBrowser()) {
throw new Error('WECHAT_BROWSER_REQUIRED');
}
return {
type: 'jsapi',
params: {
appId: orderData.appId,
timeStamp: orderData.timeStamp,
nonceStr: orderData.nonceStr,
package: orderData.package,
signType: orderData.signType,
paySign: orderData.paySign
}
};
}
isMobileApp() {
// Detect if running in mobile app environment
return typeof window.ReactNativeWebView !== 'undefined' ||
typeof window.webkit?.messageHandlers !== 'undefined';
}
isWeChatBrowser() {
const ua = navigator.userAgent.toLowerCase();
return ua.indexOf('micromessenger') !== -1;
}
async getUserOpenId(userId) {
// Retrieve stored OpenID from database
const user = await db.users.findOne({ id: userId });
return user?.wechat_openid;
}
}
// Usage
const paymentHandler = new FuyouPaymentHandler();
try {
const result = await paymentHandler.initiatePayment(
userId,
orderId,
10000, // ¥100.00
'alipay'
);
if (result.type === 'url_scheme') {
// Jump to Alipay app
window.location.href = result.url;
} else if (result.type === 'qr_code') {
// Display QR code
const qrCode = await QRCode.toDataURL(result.url);
showQRCode(qrCode);
} else if (result.type === 'jsapi') {
// Invoke WeChat Pay
invokeWeChatPay(result.params);
}
} catch (error) {
if (error.message === 'WECHAT_AUTH_REQUIRED') {
// Redirect to WeChat OAuth
redirectToWeChatAuth();
} else if (error.message === 'WECHAT_BROWSER_REQUIRED') {
// Show message to user
alert('Please open this page in WeChat to pay');
} else {
console.error('Payment failed:', error);
}
}
聚合支付小结
-
支付宝:富友等服务提供的 H5 URL 能配合 URL scheme,移动应用接入较直接。
-
微信支付:聚合商仍要遵守微信的环境限制:
- 本文的浏览器跳转方式不可用。
- JSAPI 需要公众号。
- 需要微信内置浏览器环境。
-
取舍:聚合能够统一 API、简化接入,但会增加费用,微信付款还要配置公众号。
-
实际情况:技术支持确认,有自己的公众号时,JSAPI 可通过相应参数调起支付。公众号和小程序都有各自使用这类付款接口的方式。
是否直接接入,并不改变上述微信支付路径的前提。
结论
国内支付平台的浏览器跳转方案
本文探讨了如何借应用跳转改善支付宝和微信支付体验。对使用手机相机而非应用内扫码器的海外用户,这个问题尤其重要。
主要发现
1. 支付宝在本例中可以由浏览器跳转 ✅
- URL scheme:可使用
alipays://platformapi/startapp?appId=20000067&url=<encoded_url>。 - 实现:iOS 和 Android 均能较简单地实现。
- 用户体验:相机扫码 → 浏览器打开 → 跳入支付宝。
- 第三方支持:富友等聚合服务提供兼容的 H5 链接。
- 转化率影响:原文估计海外用户有机会从约 50% 提升到约 90%。
2. 本文的微信支付场景无法从外部浏览器直接跳转 ❌
- 平台约束:腾讯限制从普通浏览器任意唤起应用。
- 无可行捷径:在微信外尝试 WeixinJSBridge、自定义 scheme 和 JSSDK 都不能达到这个目的。
- 文中采用的办法:在微信内置浏览器中使用 JSAPI 支付。
- 前提
- 需要微信公众号。
- 用户授权后获取 OpenID。
- 运行在微信浏览器中。
- 第三方限制:富友等聚合服务同样受到这些约束。
3. 第三方聚合(以富友支付为例)
好处
- 多种付款方式共用统一 API。
- 简化回调处理。
- 接入和上线更快。
- 通过一个商户账号对账。
局限
- 存在额外交易费,本文估计为 0.3%–0.6%。
- 微信支付本身的限制仍存在。
- 依赖第三方可用性。
- 微信付款仍需公众号。
如何选择接入方式
| 场景 | 建议 | 原因 |
|---|---|---|
| 量大、成本敏感 | 直接接入 | 节约聚合费用 |
| MVP 快速上线 | 聚合(富友) | 上线快 |
| 以支付宝用户为主 | 直接接入配合 URL scheme | 对本文海外用户的体验较好 |
| 以微信用户为主 | 官方 SDK 或扫码 | 文中方案不能直接从浏览器跳转 |
| 支持多个平台 | 聚合 | 统一 API 简化代码 |
| 长期企业级产品 | 直接接入 | 控制力与灵活性较高 |
按用户类型改善体验
海外用户(用相机扫码)
-
支付宝
- 实现基于 URL scheme 的浏览器跳转。
- 区分移动端与桌面环境。
- 移动端尝试跳入应用。
- 桌面展示二维码和清晰说明。
-
微信
- 认识本文路径的限制,普通浏览器不能直接调用。
- 明确提示“请在微信中打开此页面”。
- 可提供支付宝或信用卡等替代方式。
- 有条件时引导用户把付款链接分享至微信。
中国大陆用户(使用应用内扫码)
- 常规二维码方式已能满足需要。
- 支付宝和微信的内置扫码器均能衔接其付款流程。
- 无需浏览器跳转。
最终建议
-
支持移动用户时,提供支付宝 URL scheme 入口。
- 可减少海外用户流失。
- 开发工作量较小。
- 直接接入和聚合方式都可配合使用。
-
对微信支付设定符合场景的预期。
- 理解普通浏览器不能调用微信内 JSAPI。
- 网页或桌面侧优先做扫码支付。
- 原生移动应用接入官方 SDK。
- 有公众号且用户在微信内时使用 JSAPI。
-
考虑分阶段接入。
- 初期用聚合服务快速上线。
- 持续监控交易量和费用。
- 当交易量达到合适规模,再改为直接接入。
-
按用户组成优化。
- 以海外用户为主:优先改善支付宝 scheme 跳转。
- 以大陆用户为主:常规二维码即可。
- 混合用户:两条路径都提供。
-
减少在非官方微信跳转方式上的投入。
- 文中讨论的尝试都受平台限制。
- 可将精力转向支付宝体验及其他付款选项。
最后一句
对本文的接入场景而言,支付宝可以解决浏览器跳转,微信内的 JSAPI 则不能靠同一种方法从外部调起。清楚这点,才能在各平台提供的范围内为自己的用户改善转化。
对使用系统相机扫码的海外用户,支付宝 scheme 体验较顺畅。微信则要清楚提示后续步骤,并在合适时提供其他付款选项。
参考资料
Stars-one. (2023, April 25). Android 通过scheme跳转支付宝实现支付 [Android scheme-based Alipay payment integration] [Blog post]. Stars-one's Blog. https://stars-one.site/2023/04/25/android-open-alipay
weixin_49798182. (2023, November 30). 在h5中调起微信打开指定链接(不能实现,直接回怼) [Invoking WeChat to open links from H5 (cannot be implemented, direct debunking)] [Blog post]. CSDN. https://blog.csdn.net/weixin_49798182/article/details/134685327