NewCode CLOUD — 20% off your first month on all cloud VPSClaim

WeChat Pay Integration on Hong Kong VPS: China Payments Guide (2026)

· 5 min read

WeChat Pay and Alipay together account for over 94% of China’s mobile payment market. For any e-commerce or SaaS business targeting mainland Chinese customers, integrating both payment methods is essential — not optional. A Hong Kong VPS with CN2 GIA routing is the optimal hosting location: your payment callback endpoints receive WeChat Pay and Alipay notifications at 30–50ms, your API calls to Tencent and Ant Group’s mainland servers complete in under 20ms, and the Hong Kong entity structure works with both payment providers’ overseas merchant programmes.


WeChat Pay Merchant Account Types

Account Type Entity Requirement Payment Scenarios
China Domestic (境内) Mainland China business licence All scenarios including Mini Programs
WeChat Pay Global Hong Kong or overseas company H5, JSAPI, QR code for China users paying overseas merchants
Cross-border Overseas company with HK bank Settlement in HKD/USD, Chinese users pay in RMB

For a Hong Kong entity: register via WeChat Pay Global (global.pay.weixin.qq.com) or through an authorised payment service provider (PSP) like Stripe, Adyen, or 2C2P which offer WeChat Pay integration without requiring a direct Tencent merchant account.


Step 1: Nginx Preparation for Payment Callbacks

<code"># WeChat Pay and Alipay POST notifications to your callback URL
# Your VPS must be accessible over HTTPS with a valid TLS certificate

cat > /etc/nginx/sites-available/payments << 'EOF'
server {
    listen 443 ssl http2;
    server_name pay.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/pay.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/pay.yourdomain.com/privkey.pem;

    # WeChat Pay sends callbacks with 30s timeout
    proxy_read_timeout 30s;
    proxy_send_timeout 30s;

    # Allow large bodies for encrypted payment data
    client_max_body_size 2m;

    location /webhook/wechat {
        proxy_pass http://127.0.0.1:3000/webhook/wechat;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }

    location /webhook/alipay {
        proxy_pass http://127.0.0.1:3000/webhook/alipay;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }
}
EOF
ln -s /etc/nginx/sites-available/payments /etc/nginx/sites-enabled/
certbot --nginx -d pay.yourdomain.com
nginx -t && systemctl reload nginx

Step 2: WeChat Pay JSAPI (In-App Browser Payment)

<code"># npm install wechatpay-node-v3

const WxPay = require('wechatpay-node-v3')
const fs = require('fs')

const pay = new WxPay({
  appid: 'YOUR_WECHAT_APPID',
  mchid: 'YOUR_MERCHANT_ID',
  publicKey: fs.readFileSync('./wechat_pay_cert.pem'),   // From WeChat Pay dashboard
  privateKey: fs.readFileSync('./wechat_private_key.pem'),
})

// Step 1: Create unified order and get prepay_id
async function createWechatOrder(orderId, amount, openid) {
  const result = await pay.transactions_jsapi({
    description: 'Product Purchase',
    out_trade_no: orderId,           // Your unique order ID
    notify_url: 'https://pay.yourdomain.com/webhook/wechat',
    amount: {
      total: Math.round(amount * 100),  // WeChat Pay uses cents (fen)
      currency: 'CNY',
    },
    payer: { openid },               // WeChat user's OpenID
  })

  // Result contains prepay_id — use to generate payment parameters
  return result
}

// Step 2: Generate payment parameters for frontend
async function getJSAPIParams(prepayId) {
  const timestamp = Math.floor(Date.now() / 1000).toString()
  const nonceStr = Math.random().toString(36).substring(2)

  // Sign with your private key
  const params = pay.getJSAPIParams({ prepay_id: prepayId })
  return params
  // Returns: { appId, timeStamp, nonceStr, package, signType, paySign }
}

// Frontend WeChat JS-SDK call:
// wx.chooseWXPay({ ...jsapiParams, success: (res) => {} })

Payment Callback Handler

<code"># POST /webhook/wechat — WeChat Pay sends encrypted payment notification
async function handleWechatCallback(req, res) {
  const { headers, body } = req

  try {
    // Verify and decrypt WeChat Pay notification
    const result = pay.decipher_gcm(
      body.resource.ciphertext,
      body.resource.associated_data,
      body.resource.nonce,
      process.env.WECHAT_API_V3_KEY,  // Your API v3 key from merchant dashboard
    )

    if (result.trade_state === 'SUCCESS') {
      const { out_trade_no, amount, transaction_id } = result

      // Fulfill the order
      await fulfillOrder(out_trade_no, {
        wechat_transaction_id: transaction_id,
        amount_paid: amount.total / 100,  // Convert back to yuan
      })
    }

    // Must respond with SUCCESS or WeChat will retry for 24 hours
    res.json({ code: 'SUCCESS', message: '成功' })

  } catch (error) {
    console.error('WeChat callback error:', error)
    res.json({ code: 'FAIL', message: error.message })
  }
}

Step 3: Alipay Integration

<code"># npm install alipay-sdk

const AlipaySdk = require('alipay-sdk').default

const alipay = new AlipaySdk({
  appId: 'YOUR_ALIPAY_APP_ID',
  privateKey: fs.readFileSync('./alipay_private_key.pem', 'ascii'),
  alipayPublicKey: fs.readFileSync('./alipay_public_key.pem', 'ascii'),
  gateway: 'https://openapi.alipay.com/gateway.do',   // Production
  // gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // Sandbox
})

// H5 payment (WAP) — for mobile browsers
async function createAlipayH5Order(orderId, amount, subject) {
  const result = await alipay.pageExecute(
    'alipay.trade.wap.pay',
    'POST',
    {
      bizContent: {
        out_trade_no: orderId,
        subject: subject,
        total_amount: amount.toFixed(2),
        product_code: 'QUICK_WAP_WAY',
        quit_url: 'https://yourdomain.com/cart',
      },
      notifyUrl: 'https://pay.yourdomain.com/webhook/alipay',
      returnUrl: 'https://yourdomain.com/orders/success',
    }
  )
  // Redirect user to result (HTML form that auto-submits to Alipay)
  return result
}

// Alipay callback verification
async function handleAlipayCallback(req, res) {
  const params = req.body   // URL-encoded form POST

  // Verify Alipay signature
  const verified = alipay.checkNotifySign(params)
  if (!verified) return res.send('FAIL')

  if (params.trade_status === 'TRADE_SUCCESS') {
    await fulfillOrder(params.out_trade_no, {
      alipay_trade_no: params.trade_no,
      amount_paid: parseFloat(params.total_amount),
    })
  }

  // Alipay requires plain text response
  res.send('success')
}

Step 4: Unified Payment Flow

<code"># Detect user's payment preference and route accordingly
async function initiatePayment(order, req) {
  const ua = req.headers['user-agent']

  if (ua.includes('MicroMessenger')) {
    // User is in WeChat browser — use JSAPI
    const openid = await getOpenId(req)  // From WeChat OAuth
    return await createWechatOrder(order.id, order.total, openid)

  } else if (ua.includes('AlipayClient')) {
    // User is in Alipay app — use Alipay native
    return await createAlipayAppOrder(order.id, order.total)

  } else {
    // Regular mobile browser — offer choice
    return {
      wechat_pay_url: `weixin://wxpay/bizpayurl?...`,
      alipay_url: await createAlipayH5Order(order.id, order.total, order.description),
      qr_code_url: await generateQRCode(order),
    }
  }
}

Step 5: Reconciliation and Refunds

<code"># Daily reconciliation — verify all paid orders match payment records
async function dailyReconciliation(date) {
  // WeChat Pay: download trading day bill
  const wxBill = await pay.tradebill({
    bill_date: date,
    bill_type: 'SUCCESS',
  })

  // Alipay: query settlement records
  const alipayBill = await alipay.exec('alipay.data.dataservice.bill.downloadurl.query', {
    bizContent: { bill_type: 'trade', bill_date: date }
  })

  // Compare with your database records
  await compareAndAlert(wxBill, alipayBill)
}

// Process refund
async function refundOrder(orderId, refundAmount, reason) {
  const order = await Order.findById(orderId)

  if (order.payment_method === 'wechat') {
    await pay.refunds({
      out_trade_no: orderId,
      out_refund_no: `REFUND-${orderId}-${Date.now()}`,
      reason,
      amount: {
        refund: Math.round(refundAmount * 100),
        total: Math.round(order.total * 100),
        currency: 'CNY',
      },
    })
  } else if (order.payment_method === 'alipay') {
    await alipay.exec('alipay.trade.refund', {
      bizContent: {
        out_trade_no: orderId,
        refund_amount: refundAmount.toFixed(2),
        refund_reason: reason,
      }
    })
  }
}

Why HK VPS Is Optimal for China Payments

Factor HK VPS CN2 GIA US/EU Server
WeChat Pay API call latency 15–30ms to Tencent servers 150–300ms
Alipay API call latency 10–25ms to Ant Group 150–300ms
Callback notification receipt 30–50ms 200–350ms (risk of timeout)
Payment page load for CN users Sub-100ms 500ms–2s (visible degradation)
CN cross-border merchant entity HK company: straightforward Requires HK or SG entity anyway

Conclusion

WeChat Pay and Alipay integration on a Hong Kong VPS is the optimal architecture for China-facing payments — API calls to Tencent and Ant Group’s mainland servers complete in 15–30ms, payment notifications arrive reliably within 50ms, and the HK entity structure works cleanly with both payment providers’ cross-border merchant programmes. The CN2 GIA routing ensures payment pages load fast enough for Chinese mobile users to complete purchases without abandonment due to latency.

Accept China payments: Browse Server.HK Hong Kong VPS plans — all VPS plans include CN2 GIA routing to mainland China, essential for reliable payment gateway API performance.

Related articles

More in VPS & ServersServer setup guides