Enhancing Payment UX - Browser-to-App Jump for China Payment Platforms

December 1, 2025

Enhancing Payment UX: Browser-to-App Jump for China Payment Platforms

Introduction

Integrating payment systems is a critical component of any SaaS application. This guide explores techniques to enhance the user payment experience when working with Chinese payment platforms: Alipay and WeChat Pay. Specifically, we'll focus on solving the browser-to-app jump challenge that significantly impacts international users.

The Browser Jump Problem: Why It Matters

When implementing QR code payments for Chinese payment platforms, developers often encounter a critical UX issue that affects users outside mainland China:

The User Flow Problem

Traditional QR Code Payment Flow:

  1. Your application displays a payment QR code
  2. User scans the QR code with their device camera
  3. Problem: Camera scan opens the payment URL in the default browser (Safari, Chrome, etc.)
  4. User sees a payment page in the browser but cannot complete payment
  5. User must manually copy the link and open it in Alipay/WeChat app

Why This Happens:

  • Mainland China users typically use the in-app QR scanner (Alipay's or WeChat's built-in scanner)

    • These in-app scanners automatically open payment pages within the app
    • Payment flow is seamless - no browser involved
  • International/overseas users often use their phone's camera app to scan QR codes

    • Camera apps default to opening URLs in the system browser
    • Browsers cannot directly invoke Alipay/WeChat payment functions
    • This creates a broken payment experience

The Impact on User Experience

❌ 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)

Real-World Scenario

Imagine a SaaS product with international users in:

  • Hong Kong, Taiwan, Singapore: Users have Alipay/WeChat but scan with phone camera
  • International students/expats: Using Chinese payment apps but not familiar with in-app scanners
  • Business travelers: Quick transactions without app-specific knowledge

For these users, the ability to automatically jump from browser to payment app is crucial for completing transactions.

Our Goal: Seamless Payment Experience

This guide focuses on:

  1. Understanding browser-to-app jump mechanisms for Alipay and WeChat Pay
  2. Implementing URL scheme-based solutions where possible (Alipay)
  3. Working within platform constraints where necessary (WeChat Pay)
  4. Leveraging third-party aggregators (Fuyou Pay) to simplify integration
  5. Optimizing the payment flow to minimize user friction

The techniques covered here aim to enhance payment conversion rates by creating a frictionless experience for users scanning QR codes with their phone cameras.

Alipay Integration

Overview

Alipay is one of the most widely used mobile payment platforms in China. For individual developers or small businesses, direct integration with Alipay's official SDK can be challenging due to strict merchant requirements. However, there are alternative approaches using third-party payment aggregators (often called "fourth-party payment providers") or direct scheme-based integration for mobile applications.

The Challenge

Alipay doesn't allow individual developers to open payment services with webhook capabilities. This means you typically need to:

  1. Use a payment aggregation service (fourth-party provider)
  2. Implement creative solutions for mobile app integration

Mobile App Integration via URI Scheme

One elegant solution for Android/iOS applications is to leverage Alipay's URI scheme to open payment pages directly within the Alipay app, bypassing the need for complex SDK integration.

How It Works

When you scan an Alipay QR code, you're essentially opening an H5 (mobile web) link within Alipay's built-in browser. If we can programmatically trigger Alipay to open a payment H5 link, we achieve the same result as native SDK integration.

Step 1: Understanding the Alipay URI Scheme

Alipay uses a custom URI scheme that can be invoked from external applications:

alipays://platformapi/startapp?appId=20000067&url=<PAYMENT_URL>

Parameters:

  • appId=20000067: This is Alipay's internal app ID for the web browser/payment module
  • url=<PAYMENT_URL>: Your H5 payment URL (must be URL-encoded)

Step 2: Android Implementation

Here's a complete Android implementation using Kotlin:

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")
    }
}

Key Points:

  • Always check if Alipay is installed before attempting to open it
  • URL-encode the payment URL to prevent parsing errors
  • Use Intent.ACTION_VIEW to handle the custom URI scheme
  • The package name for Alipay is com.eg.android.AlipayGphone

Step 3: iOS Implementation

For iOS applications using Swift:

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 Configuration:

You need to add the Alipay URL scheme to your Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>alipays</string>
    <string>alipay</string>
</array>

Step 4: Web/Desktop Implementation

For web applications or desktop software, the traditional approach is QR code generation:

Important Note for Web URL Jumps: When implementing browser-to-app URL scheme jumps in web applications, use <a> anchor tags instead of <button> elements with onClick handlers. This ensures:

  • Better browser compatibility and native URL handling
  • Proper app switching behavior on mobile devices
  • Avoids issues with click event propagation and preventDefault
  • Works consistently across iOS and Android browsers
// ✅ 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" />`;

Backend Integration with Payment Gateway

When using a fourth-party payment provider, your backend flow typically looks like this:

// 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');
    }
});

Security Considerations

  1. Always verify webhooks: Validate the signature of payment callbacks to prevent fraud
  2. Use HTTPS: All payment-related endpoints must use HTTPS
  3. Sanitize inputs: Always validate and sanitize user inputs
  4. Store credentials securely: Never hardcode API keys; use environment variables
  5. Implement idempotency: Prevent duplicate payment processing
  6. Rate limiting: Protect your payment endpoints from abuse

Testing

For development and testing:

  1. Sandbox Environment: Most payment gateways provide sandbox credentials
  2. Test Alipay Account: Alipay provides test accounts for development
  3. Mock Webhooks: Use tools like ngrok to test payment callbacks locally
# 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

Common Issues and Solutions

Issue 1: Alipay app doesn't open

  • Solution: Verify the URL is properly encoded and the scheme is correct
  • Check if user has Alipay installed

Issue 2: Payment callback not received

  • Solution: Ensure your callback URL is publicly accessible (not localhost)
  • Check firewall and security group settings
  • Verify webhook signature validation isn't too strict during testing

Issue 3: Double payment processing

  • Solution: Implement idempotency keys
  • Check order status before processing callback
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;
}

Best Practices

  1. User Experience:

    • Show clear payment instructions
    • Display loading states during payment initialization
    • Handle timeout scenarios gracefully
  2. Error Handling:

    • Provide meaningful error messages
    • Log all payment-related errors for debugging
    • Implement retry mechanisms for failed transactions
  3. Monitoring:

    • Track payment success rates
    • Monitor webhook delivery rates
    • Set up alerts for payment failures
  4. Compliance:

    • Follow PCI DSS guidelines if handling card data
    • Comply with local payment regulations
    • Maintain audit logs for all transactions

WeChat Pay Integration

Overview

WeChat Pay (微信支付) is another dominant payment platform in China, integrated into the WeChat messaging app. Unlike Alipay, WeChat Pay has significant restrictions on programmatic app launching and URL scheme invocations, making integration more challenging for third-party applications.

The Fundamental Limitation: No Browser-to-App Jump

Important: WeChat does not allow external applications or web browsers to directly jump into the WeChat app to trigger payments using URL schemes or JavaScript bridges. This is a deliberate security and user experience design decision by Tencent.

Common Failed Approaches (Don't Waste Your Time)

Many developers attempt various methods that ultimately don't work. Here are the most common failed approaches:

❌ Approach 1: WeixinJSBridge (Doesn't Work Outside WeChat)

Some tutorials suggest using WeixinJSBridge to open links:

// ❌ 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');

Why it fails:

  • WeixinJSBridge only exists inside WeChat's built-in browser
  • It's designed for WeChat Mini Programs and in-app webviews
  • External browsers and apps don't have access to this API
  • Official documentation clearly states it's for internal WeChat use only

❌ Approach 2: WeChat JSSDK (Limited Scope)

Some try using the WeChat 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'
});

Why it fails:

  • The function wx.openUrlWithExtraWebview() doesn't exist in the JSSDK
  • The JSSDK primarily provides features like sharing, location, and scanning QR codes
  • It does not provide payment invocation capabilities for external apps
  • Payment APIs in JSSDK only work within WeChat's environment

❌ Approach 3: Custom URL Schemes (Blocked)

Unlike Alipay, WeChat has blocked custom URL scheme attempts:

// ❌ WeChat has blocked this type of invocation
const wechatScheme = "weixin://dl/business/?t=payment_url";
window.location.href = wechatScheme; // Won't work

Why it fails:

  • Tencent has intentionally blocked URL scheme-based app launching
  • Security concerns and prevention of phishing attacks
  • WeChat only opens from specific, whitelisted scenarios

What Actually Works: Official Integration Methods

Given these limitations, here are the legitimate ways to integrate WeChat Pay:

Method 1: QR Code Payment (Most Common for Desktop/Web)

This is the standard approach for web applications and desktop software:

Flow:

  1. User initiates payment on your website/app
  2. Backend generates WeChat Pay order and receives a QR code URL
  3. Display QR code to user
  4. User scans with WeChat app
  5. User completes payment in WeChat
  6. Webhook notification confirms payment

Backend Implementation (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}"`;
}

Frontend Implementation:

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);
}

Method 2: Native App Integration (Official SDK Required)

For mobile apps, you must use WeChat's official 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
}

Method 3: H5 Payment (In-WeChat Browser Only)

If your users are already inside WeChat's browser, you can use JSAPI payment:

// 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);
}

Payment Webhook Handling

Just like Alipay, you need to handle payment callbacks:

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);
}

Key Differences: WeChat vs Alipay

FeatureAlipayWeChat Pay
URL Scheme Support✅ Yes (alipays://)❌ No (blocked)
Browser-to-App Jump✅ Possible❌ Not allowed
QR Code Payment✅ Supported✅ Supported
Official SDK RequiredOptional for basic integrationRequired for mobile apps
H5 PaymentFlexibleOnly in WeChat browser
Individual Developer AccessLimitedLimited
Merchant RequirementsStrictVery strict

Recommendations

  1. For Web/Desktop Apps: Use QR code payment method exclusively
  2. For Mobile Apps: Must integrate official WeChat SDK; no shortcuts
  3. For In-WeChat Sites: Use JSAPI payment if users are already in WeChat
  4. For Third-Party Payment: Consider using aggregation services that handle the complexity

Common Pitfalls to Avoid

  1. Don't waste time trying to find workarounds for browser-to-app jumping
  2. Don't trust outdated tutorials that claim WeixinJSBridge works outside WeChat
  3. Don't attempt to reverse-engineer WeChat's app launch mechanisms
  4. Do comply with WeChat's official integration guidelines
  5. Do use official SDKs for mobile app integration

Conclusion for WeChat Pay

Unlike Alipay's more flexible integration options, WeChat Pay enforces strict boundaries. The key takeaway: there are no clever workarounds. You must follow Tencent's official integration methods, which means:

  • QR codes for web/desktop
  • Official SDK for mobile apps
  • JSAPI for in-WeChat experiences

While this may seem restrictive, it ensures security and provides a consistent user experience across the WeChat ecosystem.


Third-Party Payment Aggregators: Fuyou Pay Example

Overview

Given the strict limitations of direct Alipay and WeChat Pay integration, many developers turn to third-party payment aggregators (also called "fourth-party payment providers"). These services act as middleware, simplifying integration and providing unified APIs for multiple payment methods.

Fuyou Pay (富友支付) is a popular example of such an aggregator in China. It demonstrates both the benefits and limitations of using payment aggregators.

Fuyou Pay Integration Approaches

Approach 1: Alipay via URL Scheme + QR URL (Works ✅)

For Alipay, Fuyou Pay provides a payment URL that can be used with the URL scheme method discussed earlier:

// 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);
  }
}

This works because:

  • Fuyou provides an H5 payment URL
  • The URL can be opened in Alipay's browser via the alipays:// scheme
  • The same URL can be converted to a QR code for desktop users

Approach 2: WeChat Pay via JSAPI (Limited ⚠️)

For WeChat Pay, Fuyou Pay can only use the JSAPI method, which has significant limitations:

Critical Requirement: You must have your own WeChat Official Account (公众号) or Mini Program (小程序).

// 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
  };
}

Frontend Implementation (Must be in WeChat Browser):

// 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;
}

Prerequisites for Fuyou WeChat JSAPI

According to the tech support conversation, using Fuyou's JSAPI for WeChat Pay requires:

  1. Your own WeChat Official Account (公众号) or Mini Program (小程序)
  2. User authorization - Users must authorize your Official Account to get their OpenID
  3. H5 application - Your app must be accessible via mobile web browser
  4. WeChat browser environment - Payment can only be triggered inside WeChat

Getting User's WeChat OpenID

Before you can process WeChat payments, you need the user's 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');
  }
});

Comparison: Direct Integration vs Fuyou Pay

FeatureDirect IntegrationFuyou Pay (Aggregator)
Setup ComplexityHigh (separate registration for each platform)Medium (single registration)
Alipay URL Scheme✅ Direct support✅ Supported via H5 URL
WeChat URL Scheme❌ Not possible❌ Still not possible
WeChat JSAPIRequires Official Account + Merchant Account✅ Requires only Official Account
QR Code Payments✅ Both platforms✅ Both platforms
Transaction FeesLower (direct fees only)Higher (platform fees + aggregator fees)
Unified API❌ Different APIs per platform✅ Single unified API
Webhook HandlingSeparate for each platformUnified webhook format

Limitations of Aggregator Approach (Fuyou Pay)

  1. WeChat Pay Still Restricted:

    • Cannot jump from external browser/app to WeChat
    • Still requires WeChat browser environment
    • Must have Official Account (additional setup)
  2. Additional Costs:

    • Aggregator fees on top of payment platform fees
    • Typically 0.3% - 0.6% additional cost per transaction
  3. Dependency Risk:

    • Reliant on third-party service availability
    • Potential for service disruptions
    • Less control over payment flow
  4. Compliance Considerations:

    • Aggregators may have different compliance requirements
    • Some industries may require direct integration

When to Use Fuyou Pay (or Similar Aggregators)

Use aggregators when:

  • You need to support multiple payment methods quickly
  • You want unified webhook handling
  • You're building an MVP and want faster time-to-market
  • Transaction volume is low-to-medium (fees are acceptable)
  • You need simplified accounting (single merchant account)

Use direct integration when:

  • Transaction volume is high (save on aggregator fees)
  • You need maximum control over payment flow
  • You're building a long-term, large-scale application
  • You require specific features not offered by aggregators
  • Regulatory requirements mandate direct integration

Complete Example: Unified Payment Handler

Here's a complete example that handles both Alipay and WeChat Pay via Fuyou:

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);
  }
}

Key Takeaways for Third-Party Aggregators

  1. Alipay: Aggregators like Fuyou can provide H5 URLs that work with the URL scheme method, making mobile app integration straightforward.

  2. WeChat Pay: Even with aggregators, you cannot bypass WeChat's restrictions:

    • No browser-to-app jumping
    • JSAPI requires Official Account
    • Must be in WeChat browser environment
  3. Trade-offs: Aggregators simplify integration and provide unified APIs, but add costs and complexity for WeChat Pay (Official Account requirement).

  4. Real-World Reality: As confirmed by tech support, JSAPI can use the parameters to directly invoke WeChat Pay, but only if you have your own Official Account (公众号). Both Official Accounts and Mini Programs use the JSAPI interface for payment.

The fundamental WeChat Pay limitations remain unchanged regardless of whether you use direct integration or an aggregator.

Conclusion

Summary: Browser-to-App Jump Solutions for Chinese Payment Platforms

This guide explored techniques to enhance payment user experience by enabling seamless browser-to-app jumps for Alipay and WeChat Pay—a critical requirement for international users who scan QR codes with their phone cameras rather than in-app scanners.

Key Findings

1. Alipay: Browser Jump is Possible ✅

  • URL Scheme Method: alipays://platformapi/startapp?appId=20000067&url=<encoded_url> works reliably
  • Implementation: Simple to implement on both iOS and Android
  • User Experience: Seamless - users scan QR with camera → browser opens → auto-jumps to Alipay app
  • Third-Party Support: Payment aggregators like Fuyou Pay fully support this approach
  • Conversion Rate Impact: Can improve from ~50% to ~90% for international users

2. WeChat Pay: Browser Jump is Not Possible ❌

  • Platform Restriction: Tencent has intentionally blocked all browser-to-app jump mechanisms
  • No Workarounds: WeixinJSBridge, URL schemes, and JSSDK approaches all fail outside WeChat browser
  • Only Solution: JSAPI payment within WeChat's built-in browser
  • Requirements:
    • Must have WeChat Official Account (公众号)
    • Users must authorize and provide OpenID
    • Only works inside WeChat browser environment
  • Third-Party Limitation: Even aggregators like Fuyou Pay cannot bypass these restrictions

3. Third-Party Aggregators (Fuyou Pay Example)

Advantages:

  • Unified API for multiple payment methods
  • Simplified webhook handling
  • Faster integration and time-to-market
  • Single merchant account for accounting

Limitations:

  • Additional transaction fees (0.3% - 0.6%)
  • Cannot bypass WeChat Pay's fundamental restrictions
  • Dependency on third-party service availability
  • Still requires WeChat Official Account for WeChat Pay

Decision Matrix: Choosing Your Integration Approach

ScenarioRecommended ApproachReason
High volume, cost-sensitiveDirect integrationSave aggregator fees
MVP, quick launchAggregator (Fuyou)Faster time-to-market
Alipay-primary usersDirect + URL schemeBest UX for international users
WeChat-primary usersOfficial SDK or QR onlyNo browser jump possible
Multi-platform supportAggregatorUnified API simplifies code
Long-term, enterpriseDirect integrationMaximum control and flexibility

UX Optimization Strategies by User Type

For International/Overseas Users (Camera Scanners):

  1. Alipay Payment:

    • Implement URL scheme-based browser jump
    • Detect mobile vs desktop environment
    • Mobile: Auto-jump to app
    • Desktop: Display QR code with clear instructions
  2. WeChat Payment:

    • Accept the limitation - no browser jump possible
    • Provide clear instructions: "Please open this page in WeChat"
    • Consider offering alternative payment methods (Alipay, credit card)
    • If possible, direct users to share payment link to WeChat contacts

For Mainland China Users (In-App Scanners):

  • Traditional QR code approach works perfectly
  • Both Alipay and WeChat in-app scanners handle payments natively
  • No browser jump needed

Final Recommendations

  1. Always implement Alipay URL scheme jump if supporting mobile users

    • Dramatic improvement in conversion rates for international users
    • Minimal development effort
    • Works with both direct integration and aggregators
  2. Set realistic expectations for WeChat Pay

    • Understand that browser-to-app jump is impossible
    • Focus on QR code payments for web/desktop
    • Official SDK for native mobile apps
    • JSAPI only if you have Official Account and users are in WeChat
  3. Consider hybrid approach

    • Use aggregator for initial launch (speed to market)
    • Monitor transaction volume and fees
    • Migrate to direct integration if volume justifies it
  4. Optimize for your user base

    • If primarily international users: Prioritize Alipay with URL scheme
    • If primarily mainland users: Traditional QR codes work fine
    • If mixed audience: Implement both approaches
  5. Don't waste time trying to find WeChat browser jump workarounds

    • Tencent has closed all loopholes
    • Focus energy on Alipay optimization and alternative payment methods

The Bottom Line

Browser-to-app jump is a solved problem for Alipay and an impossible problem for WeChat Pay. Understanding this reality allows you to build payment experiences that work within each platform's constraints while maximizing conversion rates for your specific user base.

For international users scanning with phone cameras, Alipay URL scheme integration provides excellent UX. For WeChat Pay, accept the limitations and focus on clear user guidance and alternative payment options.


References

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

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-01). Enhancing Payment UX - Browser-to-App Jump for China Payment Platforms. https://caiborui.com/blog/2025-12-01-en-payment-integration

@misc{borui2025-ed70bae6,
  author = {borui},
  title = {{Enhancing Payment UX - Browser-to-App Jump for China Payment Platforms}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-01-en-payment-integration}
}