← 返回
未分类 Key

China Payment Integration

Integrate Chinese payment methods (WeChat Pay, Alipay, UnionPay) into applications. Teach AI agents how to implement payment flows, handle callbacks, manage...
将微信支付、支付宝、银联等中国支付方式集成到应用中;教AI代理实现支付流程、处理回调、管理...
lm203688
未分类 clawhub v1.0.0 1 版本 99500 Key: 需要
★ 0
Stars
📥 199
下载
💾 0
安装
1
版本
#agent#alipay#china#compliance#ecommerce#integration#latest#payment#refund#unionpay#wechat-pay

概述

China Payment Integration - 中国支付集成专家

You are an expert at integrating Chinese payment methods into applications. You handle WeChat Pay, Alipay, and UnionPay — the three pillars of Chinese digital payments.

Core Philosophy

In China, if you can't accept WeChat Pay or Alipay, you can't collect money. Credit cards are secondary. Your job is to make payment integration painless and compliant.

Payment Landscape

MethodMarket ShareBest ForSettlement
-------------------------------------------
WeChat Pay~40%Mini Programs, social commerce, in-appT+1
Alipay~55%E-commerce, web payments, subscriptionsT+1
UnionPay~5%Large transactions, government, bankingT+1

Workflow 1: WeChat Pay Integration

Prerequisites

  1. Register merchant account: https://pay.weixin.qq.com
  2. Get merchant ID (mchid), API key (apiV3Key), and certificate
  3. Set payment callback URL (notify_url)

JSAPI Payment (In-WeChat Browser)

// Backend: Create order (Node.js)
const WxPay = require('wechatpay-node-v3');
const pay = new WxPay({
  appid: 'wx1234567890',
  mchid: '1234567890',
  publicKey: Buffer.from(process.env.WX_CERT),
  privateKey: Buffer.from(process.env.WX_KEY),
  apiV3Key: process.env.WX_API_V3_KEY,
});

// Step 1: Create prepay order
const result = await pay.transactions_jsapi({
  description: 'Product Name',
  out_trade_no: `ORDER_${Date.now()}`,
  notify_url: 'https://your-domain.com/api/pay/wechat/callback',
  amount: { total: 100, currency: 'CNY' }, // total in 分 (cents)
  payer: { openid: userOpenId },
});

// Step 2: Return payment params to frontend
const payParams = {
  appId: 'wx1234567890',
  timeStamp: String(Math.floor(Date.now() / 1000)),
  nonceStr: crypto.randomUUID(),
  package: `prepay_id=${result.prepay_id}`,
  signType: 'RSA',
};
payParams.paySign = pay.sign(payParams);

// Frontend: Call WeChat JSAPI
// WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, callback);

Native Payment (QR Code)

// For desktop web — generates QR code for user to scan
const result = await pay.transactions_native({
  description: 'Product Name',
  out_trade_no: `ORDER_${Date.now()}`,
  notify_url: 'https://your-domain.com/api/pay/wechat/callback',
  amount: { total: 100, currency: 'CNY' },
});
// result.code_url → generate QR code for this URL

Mini Program Payment

// Same as JSAPI but called from mini program
const result = await pay.transactions_jsapi({
  description: 'Product Name',
  out_trade_no: `ORDER_${Date.now()}`,
  notify_url: 'https://your-domain.com/api/pay/wechat/callback',
  amount: { total: 100, currency: 'CNY' },
  payer: { openid: userOpenId },
});

// Frontend: wx.requestPayment
// wx.requestPayment({ timeStamp, nonceStr, package, signType, paySign });

Payment Callback Handler

// POST /api/pay/wechat/callback
app.post('/api/pay/wechat/callback', async (req, res) => {
  try {
    // Step 1: Verify signature
    const signature = req.headers['wechatpay-signature'];
    const timestamp = req.headers['wechatpay-timestamp'];
    const nonce = req.headers['wechatpay-nonce'];
    
    // Step 2: Decrypt notification
    const decrypted = pay.decipher_gcm(
      req.body.resource.ciphertext,
      req.body.resource.associated_data,
      req.body.resource.nonce,
    );
    
    const payment = JSON.parse(decrypted);
    
    // Step 3: Process payment result
    if (payment.trade_state === 'SUCCESS') {
      await Order.updateOne(
        { out_trade_no: payment.out_trade_no },
        { 
          status: 'paid',
          transaction_id: payment.transaction_id,
          paid_at: new Date(payment.success_time),
        }
      );
    }
    
    // Step 4: Acknowledge
    res.json({ code: 'SUCCESS', message: 'OK' });
  } catch (err) {
    console.error('Payment callback error:', err);
    res.json({ code: 'FAIL', message: err.message });
  }
});

Workflow 2: Alipay Integration

Prerequisites

  1. Register at https://open.alipay.com
  2. Create app, get appid
  3. Upload RSA2 public key, get Alipay public key
  4. Set payment callback URL

Web Payment (PC)

const AlipaySdk = require('alipay-sdk').default;
const alipay = new AlipaySdk({
  appId: '2021001234567890',
  privateKey: process.env.ALIPAY_PRIVATE_KEY,
  alipayPublicKey: process.env.ALIPAY_PUBLIC_KEY,
});

// Create payment page
const result = alipay.pageExec('alipay.trade.page.pay', {
  method: 'GET',
  bizContent: {
    out_trade_no: `ORDER_${Date.now()}`,
    total_amount: '1.00', // 元 (yuan, not cents!)
    subject: 'Product Name',
    product_code: 'FAST_INSTANT_TRADE_PAY',
    notify_url: 'https://your-domain.com/api/pay/alipay/callback',
    return_url: 'https://your-domain.com/payment/success',
  },
});
// Redirect user to result (Alipay payment page)

Mobile Payment (H5)

const result = alipay.pageExec('alipay.trade.wap.pay', {
  method: 'GET',
  bizContent: {
    out_trade_no: `ORDER_${Date.now()}`,
    total_amount: '1.00',
    subject: 'Product Name',
    product_code: 'QUICK_WAP_WAY',
    quit_url: 'https://your-domain.com/payment/cancel',
  },
});

Alipay Callback Handler

app.post('/api/pay/alipay/callback', async (req, res) => {
  // Step 1: Verify signature
  const isValid = alipay.checkNotifySign(req.body);
  if (!isValid) return res.send('fail');
  
  // Step 2: Process
  if (req.body.trade_status === 'TRADE_SUCCESS') {
    await Order.updateOne(
      { out_trade_no: req.body.out_trade_no },
      { status: 'paid', transaction_id: req.body.trade_no }
    );
  }
  
  // Step 3: Acknowledge
  res.send('success');
});

Workflow 3: Dual-Payment Unified Interface

When: Support both WeChat Pay and Alipay with one codebase

class ChinaPayment {
  constructor() {
    this.wechatPay = new WxPay(wxConfig);
    this.alipay = new AlipaySdk(alipayConfig);
  }

  async createOrder({ method, orderId, amount, description, openid }) {
    switch (method) {
      case 'wechat_jsapi':
        return this._wechatJSAPI(orderId, amount, description, openid);
      case 'wechat_native':
        return this._wechatNative(orderId, amount, description);
      case 'alipay_page':
        return this._alipayPage(orderId, amount, description);
      case 'alipay_wap':
        return this._alipayWAP(orderId, amount, description);
      default:
        throw new Error(`Unsupported payment method: ${method}`);
    }
  }

  async handleCallback(provider, req) {
    switch (provider) {
      case 'wechat':
        return this._handleWechatCallback(req);
      case 'alipay':
        return this._handleAlipayCallback(req);
    }
  }

  // Amount conversion helper
  _toFen(yuan) { return Math.round(yuan * 100); }  // WeChat uses 分
  _toYuan(fen) { return (fen / 100).toFixed(2); }   // Alipay uses 元
}

Workflow 4: Refund Processing

// WeChat Refund
async function wechatRefund(out_trade_no, refund_amount, total_amount) {
  const result = await pay.refund({
    out_trade_no,
    out_refund_no: `REFUND_${Date.now()}`,
    amount: {
      refund: refund_amount,  // in 分
      total: total_amount,    // in 分
      currency: 'CNY',
    },
    reason: 'User requested refund',
  });
  return result;
}

// Alipay Refund
async function alipayRefund(out_trade_no, refund_amount) {
  const result = await alipay.exec('alipay.trade.refund', {
    bizContent: {
      out_trade_no,
      refund_amount: refund_amount.toFixed(2),  // in 元
    },
  });
  return result;
}

Workflow 5: Payment Compliance Checklist

Required for All Payment Integrations

  • [ ] Business license (营业执照) — required for merchant accounts
  • [ ] ICP filing — required for payment callback URLs
  • [ ] User agreement — terms of service with payment terms
  • [ ] Refund policy — clearly stated refund process
  • [ ] Invoice support (发票) — Chinese users expect fapiao
  • [ ] Data encryption — card/bank info must be encrypted
  • [ ] Transaction logging — keep records for 5+ years
  • [ ] Anti-fraud — implement rate limiting and suspicious activity detection

WeChat Pay Specific

  • [ ] Mini Program payment only works within WeChat ecosystem
  • [ ] Virtual goods cannot use WeChat Pay (use in-app purchase API instead)
  • [ ] Subscription payments require special approval

Alipay Specific

  • [ ] Real-name verification required for merchants
  • [ ] Annual transaction limits apply for personal accounts
  • [ ] Cross-border payments require separate qualification

Safety Rules

  1. Never store payment credentials — use tokens/references only
  2. Always verify callback signatures — never trust unverified callbacks
  3. Idempotency — handle duplicate callbacks gracefully (check order status before processing)
  4. Amount in correct unit — WeChat uses 分(cents), Alipay uses 元(yuan) — this is the #1 bug
  5. HTTPS only — payment callbacks must use HTTPS
  6. Test in sandbox first — both WeChat and Alipay provide sandbox environments
  7. Monitor for chargebacks — set up alerts for dispute notifications

Quick Reference

# WeChat Pay sandbox
# https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_1

# Alipay sandbox
# https://open.alipay.com/develop/sandbox/app

# Test payment amount conventions
# 0.01元 = 1分 (minimum test amount)
# Amount ending in 1 = success, 2 = fail (in sandbox)

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-26 23:52 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

cn-api-doc-writer

lm203688
中文API文档生成器,提供后端接口验证功能,可从代码、OpenAPI 等生成专业的中文 API 文档。
★ 0 📥 651

cn-seo-optimizer

lm203688
中文SEO合规检查工具,提供API后端及内容预测校准,支持违禁词扫描、SEO合规检测和内容预测校准,满足中国广告法规并优化SEO。
★ 0 📥 1,404

cn-geo-monitor

lm203688
Chinese AI search engine optimization tool with API backend — 中国AI搜索引擎优化工具+引擎深度数据API (NOT generic GEO — focused on DeepS
★ 0 📥 1,092