阿里云主机折上折
  • 微信号
Current Site:Index > Payment and Login (WeChat Pay, Alipay)

Payment and Login (WeChat Pay, Alipay)

Author:Chuan Chen 阅读数:20712人阅读 分类: uni-app

Payment and Login (WeChat Pay, Alipay)

uni-app, as a cross-platform development framework, supports the integration of WeChat Pay and Alipay. These two payment methods are highly frequent in mobile applications, and developers need to be familiar with their integration processes and common issue handling.

WeChat Pay Integration

The implementation of WeChat Pay in uni-app primarily relies on the uni.requestPayment API. Before integration, ensure that the application has been registered and approved on the WeChat Open Platform.

// WeChat Pay example code
uni.requestPayment({
  provider: 'wxpay',
  orderInfo: {}, // Payment parameters returned by the server
  success: function(res) {
    console.log('Payment successful:' + JSON.stringify(res));
  },
  fail: function(err) {
    console.log('Payment failed:' + JSON.stringify(err));
  }
});

Key parameter explanations:

  • timeStamp must be a string-type timestamp
  • nonceStr a random string within 32 characters
  • package fixed format as prepay_id=xxx
  • signType signature algorithm, usually MD5 or HMAC-SHA256

Common issue handling:

  1. Signature error: Verify the merchant key is correct and parameter order matches the documentation
  2. No callback after payment completion: Check if the app was killed by the system; consider adding a local storage flag
  3. Cross-platform compatibility issues: iOS and Android package names/bundle IDs must match those registered on the WeChat Open Platform

Alipay Implementation

Alipay integration is relatively simpler but requires attention to differences between sandbox and production environments. uni-app also provides a unified API:

// Alipay example
uni.requestPayment({
  provider: 'alipay',
  orderInfo: 'partner="2088xxxx"&seller_id="xxx@xxx.com"&...', // Complete order string
  success: function(res) {
    uni.showToast({ title: 'Payment successful' });
  },
  fail: function(err) {
    console.error('Payment exception', err);
  }
});

Special notes:

  • The order string must include all required parameters
  • Android platform requires application signature configuration
  • Server-side must implement asynchronous notification verification

Payment Status Verification

Payment status verification after success should be completed on the server side, not relying on client-side returns. Recommended flow:

  1. Client receives payment success callback
  2. Query order status from the server
  3. Update UI based on server response
function verifyPayment(orderNo) {
  uni.request({
    url: '/api/payment/verify',
    data: { orderNo },
    success(res) {
      if(res.data.paid) {
        // Actual payment success handling
      } else {
        // Payment incomplete handling
      }
    }
  });
}

Multi-Platform Compatibility Handling

Different platforms have varying payment implementations, requiring compatibility handling:

// Platform detection example
let provider;
// #ifdef MP-WEIXIN
provider = 'wxpay';
// #endif
// #ifdef APP-PLUS
provider = 'alipay'; // Default to Alipay
// #endif

uni.requestPayment({
  provider,
  // ...other parameters
});

Login Authorization Integration

Payments often need to integrate with login systems. WeChat login example:

uni.login({
  provider: 'weixin',
  success(res) {
    const code = res.code; // Obtain temporary credential
    uni.request({
      url: '/api/wxlogin',
      method: 'POST',
      data: { code },
      success(userInfo) {
        // Login success handling
      }
    });
  }
});

Alipay authorization login differs slightly:

uni.getUserInfo({
  provider: 'alipay',
  success(res) {
    const authCode = res.code;
    // Send authCode to server to exchange for user info
  }
});

Security Considerations

  1. Payment keys must be stored on the server; never include them in client-side code
  2. Amount verification must be completed on the server
  3. Regularly check certificate and key validity
  4. Implement anti-replay attack mechanisms, such as order number uniqueness verification
  5. Key logs require desensitization

Performance Optimization Suggestions

For high-frequency payment scenarios:

  • Pre-create orders: Create them before users enter the payment flow
  • Cache payment results locally: Avoid duplicate queries
  • Combine payment verification requests: Reduce network overhead
  • Use WebSocket to receive payment result notifications
// WebSocket listening example
const socket = uni.connectSocket({
  url: 'wss://yourdomain.com/ws'
});

socket.onMessage(res => {
  const data = JSON.parse(res.data);
  if(data.type === 'payment_success') {
    // Update order status
  }
});

Error Handling Mechanism

Comprehensive error handling should include:

  • Network exception retry mechanism
  • Automatic cancellation on payment timeout
  • Guidance to alternative payment methods for insufficient balance
  • Fallback solutions during system congestion
// Payment example with retry
function payWithRetry(orderInfo, retryCount = 3) {
  uni.requestPayment({
    provider: 'wxpay',
    orderInfo,
    success() { /*...*/ },
    fail(err) {
      if(retryCount > 0) {
        setTimeout(() => payWithRetry(orderInfo, retryCount - 1), 1000);
      } else {
        uni.showModal({
          content: 'Payment failed, please try again later',
          showCancel: false
        });
      }
    }
  });
}

Testing Verification Points

Payment functionality testing must cover:

  1. Normal payment flow
  2. Payment interruption recovery
  3. Duplicate payment handling
  4. Refund flow verification
  5. Performance under different network environments
  6. Internationalization scenarios (e.g., multi-currency payments)

Recommend establishing automated test cases:

// Test case example
describe('Payment module test', () => {
  it('Should complete WeChat Pay successfully', async () => {
    const res = await mockPayment('wxpay');
    expect(res).toHaveProperty('paid', true);
  });
  
  it('Should handle payment timeout', async () => {
    mockNetworkTimeout();
    const res = await payWithRetry(testOrder, 2);
    expect(res).toHaveProperty('error', 'timeout');
  });
});

User Experience Optimization

Details to improve payment conversion:

  • Keep the payment process to no more than 3 steps
  • Automatically remember frequently used payment methods
  • Provide clear payment progress feedback
  • Give specific reasons and solutions for failures
  • Guide next steps after payment completion
// Payment progress feedback example
uni.showLoading({
  title: 'Processing payment',
  mask: true
});

uni.requestPayment({
  // ...parameters
  complete() {
    uni.hideLoading();
  }
});

Server-Side Requirements

Client-side payments require server-side support for the following interfaces:

  1. Pre-payment order creation interface
  2. Payment result query interface
  3. Refund processing interface
  4. Payment notification verification interface
  5. Order status synchronization interface

Typical interface response format:

{
  "code": 200,
  "data": {
    "orderNo": "20231101123456",
    "paid": true,
    "amount": 99.00,
    "paymentTime": "2023-11-01 12:34:56"
  }
}

Payment Data Analysis

Recommended payment-related metrics to collect:

  • Payment success rate
  • Average payment duration
  • Proportion of payment methods
  • Failure reason distribution
  • User payment behavior paths

Can be reported via custom events:

uni.reportAnalytics('payment_start', {
  payment_type: 'wxpay',
  amount: 100
});

International Payment Adaptation

For overseas users, consider:

  1. Automatic currency conversion
  2. Integration of local mainstream payment methods
  3. Multi-language payment interfaces
  4. Exchange rate fluctuation handling
  5. Cross-border payment compliance requirements
// Multi-currency payment example
function formatCurrency(amount, currency) {
  return new Intl.NumberFormat(undefined, {
    style: 'currency',
    currency
  }).format(amount);
}

// Output: ¥100.00 or $100.00 etc.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.