Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating WeChat Pay into Mini Programs

Tech 1

The payment architecture relies on a secure interaction between the client-side mini program, the merchant backend, and the WeChat Pay server.

Transaction Workflow

  1. The user triggers a checkout action within the mini program.
  2. The client sends a payment initiation request to the merchant server.
  3. The backend communicates with the WeChat Pay unified order API.
  4. WeChat Pay returns a prepayment ID (prepay_id) to the back end.
  5. The server signs the necessary parameters and sends them back to the client.
  6. The mini program invokes the payment interface using the signed parameters.

Implementation Details

User Identification

Before processing transactions, the system must identify the user via their OpenID. This is achieved through the login credential exchange mechanism.

// Helper function to retrieve user OpenID
async function fetchUserIdentifier() {
  try {
    const loginResult = await wx.login();
    if (loginResult.code) {
      const response = await wx.request({
        url: 'https://api.example.com/auth/exchange',
        method: 'POST',
        data: { credential: loginResult.code }
      });
      return response.data.userOpenId;
    }
    throw new Error('Login credential missing');
  } catch (error) {
    console.error('Authentication failed:', error);
    return null;
  }
}

Initiating the Transaction

Too invoke the native payment UI, specific signed parameters are required. These must be generated by the backend to ensure security. The client should not attempt to sign payloads locally.

Required fields for the payment invocation include:

  • timeStamp: Current Unix timestamp.
  • nonceStr: Random string to prevent replay attacks.
  • package: The prepayment ID string (format: prepay_id=...).
  • signType: Encryption method (e.g., HMAC-SHA256 or MD5).
  • paySign: The signature generated by the server.
// Function to execute payment request
async function executePayment(paymentParams) {
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      timeStamp: paymentParams.timestamp,
      nonceStr: paymentParams.randomString,
      package: paymentParams.prepayPackage,
      signType: paymentParams.algorithm,
      paySign: paymentParams.signature,
      success: (result) => {
        resolve({ status: 'success', details: result });
      },
      fail: (error) => {
        reject({ status: 'failed', error: error });
      }
    });
  });
}

Verifying Transaction Status

While the client receives immediate feedback, the definitive transaction status is communicated via server-to-server notifications. The client should query the backend to confirm the final state.

// Verify order status with backend
async function confirmOrderStatus(orderId) {
  const verification = await wx.request({
    url: 'https://api.example.com/orders/verify',
    data: { transactionId: orderId }
  });
  
  if (verification.data.isValid) {
    // Update UI for successful purchase
    handleSuccessfulCheckout();
  } else {
    // Handle verification failure
    handleCheckoutError();
  }
}

Configuration Requirements

Successful integration requires proper setup on the WeChat Merchant Platform.

  1. Merchant Account: Complete registration and bussiness verification.
  2. API Credentials: Configure API keys and set up secure callback URLs for notifications.
  3. Mini Program Settings: Bind the Mini Program AppID to the merchant account in the developer console.
  4. Security: Ensure all communication uses HTTPS and signatures adhere to the latest security standards.

Complete Integration Example

The following snippet demonstrates chaining authentication and payment logic.

async function completeCheckoutFlow(amount) {
  const userOpenId = await fetchUserIdentifier();
  
  if (!userOpenId) {
    console.warn('User identification failed');
    return;
  }

  const orderData = await wx.request({
    url: 'https://api.example.com/payments/create',
    method: 'POST',
    data: { uid: userOpenId, amount: amount }
  });

  try {
    await executePayment(orderData.data);
    await confirmOrderStatus(orderData.data.orderId);
  } catch (err) {
    console.error('Payment process interrupted', err);
  }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.