tencent cloud

Mini Game Payment Practical Tutorial
Last updated: 2025-11-27 15:11:03
Mini Game Payment Practical Tutorial
Last updated: 2025-11-27 15:11:03

Introduction

Typically, users trigger payment actions within mini games in scenarios such as, but not limited to, purchasing in-game items, unlocking levels or content, subscribing to memberships or services, reviving or continuing the game, sending virtual gifts or engaging in social interactions, accelerating game progress, taking advantage of limited-time offers or promotions, impulse buying driven by emotions, and fulfilling achievement or collection needs.Unlike e-commerce shopping or lifestyle services, the payments triggered in these scenarios involve virtual goods. This type of consumption involving virtual goods is referred to as "virtual payments."

Definition

Virtual payment refers to a payment method where users use virtual currency (such as game coins, points, tokens, etc.) to purchase virtual goods or services. Unlike traditional cash or card payments, virtual payments typically occur on digital platforms or applications, such as games, social platforms, and online education.
Note:
Most platforms require developers to use their built-in payment systems for virtual payment transactions (for example, Apple App Store and Google Play require the use of Apple Pay and Google Play Billing), and different platforms have varying commission rates for virtual payments.

Implementation path for virtual payments in superapps

Prerequisites

Ensure your superapp meets the following conditions:
The superapp has implemented or integrated a payment channel.
The payment channel supports merchant management.
Note:
For details on the merchant concept, see: Payment and Merchant Practical Tutorial.

Technical solution for virtual payment in mini games

Differences between payment solutions in mini games and mini programs

The payment process in mini games is mostly like that of mini programs, with only small differences in the workflow:
Like mini programs, the method for applying for keys and merchant accounts is the same; however, the corresponding field names may differ.
For mini game payments, the request to the Super App as a Service (SAS) backend is triggered directly by the mini game frontend. In contrast, for mini program payments, the request is initiated by the mini program backend.
When purchasing items, mini games require developers to register the in-game items for sale in the console beforehand.
During the purchase process, mini games do not generate an order ID but instead directly trigger the payment process.
Mini game virtual item registration
Developers with the appropriate permissions should log in to the console to register virtual items for sale in the mini game. Once approved by the superapp, the mini game can initiate the purchase process.

Preparations

Encryption, decryption and signature
Virtual item adding
Refer to Direct Purchase of Mini Game Items, and navigate to section 4 Virtual item management.
Example payment flowchart
The overall flowchart for mini game payments is illustrated below, divided into three main processes: Order placement and payment, delivery notification, and payment result confirmation.

Order placement and payment
1. Order placement
When developing a mini game, developers must configure the push notification settings in the console under Commercialization - Virtual payment - Basic configurations, and enable the item delivery push notifications under Commercialization - Virtual payment - Virtual item management to receive the callback requests after a successful order placement. For additional development considerations, see Virtual Payment.
When a user initiates an item purchase in the mini game, the mini game frontend should first confirm payment-related information with the mini game backend, passing along the relevant data for the item purchase.
Upon receiving the order request, the mini game backend must use the secret key to complete data signing and create an order (at this point, the payment is not yet completed, and the order should be in an unpaid status). The signing key must be securely stored on the mini game backend. For data security, the developer's server should not expose the key to the mini game frontend or provide it externally.
The mini game server returns the generated signature data (signData, paySig, signature) to the mini game frontend. For an example of signing on the mini game backend, please refer to the following:

signData
is a JSON string generated by the mini game backend using the item purchase data passed from the mini game frontend during the order placement. For parameter descriptions. For parameter descriptions, see signData parameter description. Example:
'{"mode":"goods","buyQuantity":1,"env":0,"currencyType":"USD","platform":"android","productId":"testproductId","goodsPrice":10,"outTradeNo":"xxxxxx","attach":"testdata"}'

For the generation of paySig, see the following parameters:

Field
Type
Description
signData
string
Original payment string.
appkey
string
Payment signature key (stored by the mini game backend and exchanged with the superapp backend).
method
string
Fixed format: requestMidasPaymentGameItem.
Example:
import hmac
import hashlib
import urllib.parse

# signData: The original payment string. Note that signData must be exactly the same as the parameters sent from the frontend, including spaces and line breaks. It is recommended to generate and send it from the backend.
# appkey: The payment key
# method: The signing method: requestMidasPaymentGameItem.
def gen_pay_sig(signData, appkey, method):
need_encode_body = method + '&' + sign_data
print(need_encode_body)
return hmac.new(key=appkey.encode('utf-8'), msg=need_encode_body.encode('utf-8'),
digestmod=hashlib.sha256).hexdigest()

For the generation of signature, see the following parameters:

Field
Type
Description
session_key
string
User login session. For the retrieval method, see Log in to the mini program
post_body
string
signData Original payment string.
Example:
import hmac
import hashlib
import json
import time

def calc_signature(post_body, session_key):
## User login state signature algorithm
## Args:
## post_body - HTTP POST body
## session_key - Current user's valid session_key, refer to the jscode2session API
## Returns:
## User login state signature
"""
need_sign_msg = post_body
signature = hmac.new(key = session_key.encode('utf-8'), msg = need_sign_msg.encode('utf-8'),
digestmod=hashlib.sha256).hexdigest()
return signature
2. Payment
Once the mini game frontend receives the callback indicating that the order has been successfully created by the mini game backend, it can call the wx.RequestMidasPaymentGameItem provided by the SAS SDK to initiate superapp payment. The signature data returned by the mini game backend should be passed in. Below is an example of the mini game frontend code:
wx.requestMidasPaymentGameItem({
signData: '{"mode":"goods","buyQuantity":1,"env":0,"currencyType":"USD","platform":"android","productId":"testproductId","goodsPrice":10,"outTradeNo":"xxxxxx","attach":"testdata"}',
paySig: 'd0b8bbccbe34ed11549bcfd6602b08711f4acc0965253a949cd6a2b895152f9d',
signature: 'd0b8bbccbe34ed11549bcfd6602b08711f4acc0965253a949cd6a2b895152f9d',
success({errMsg, errCode }) {
console.log('pay successfully ', errCode);
},
fail({ errMsg, errCode }) {
console.error(errMsg, errCode)
}
After receiving the request, the SAS SDK will initiate a request to the SAS backend (openServer) on behalf of the mini game.
Upon receiving the request, the SAS backend (openServer) will verify whether the virtual item has been registered on SAS and check if each item's ID and price match the registered data. It will then forward the request to the superapp backend's create-prepay-order API. For the API parameters, see Mini game order creation API.
When the superapp receives the direct purchase payment request for the game item, it needs to complete the signature verification and check the payment information and business-related parameters for the order to ensure that the purchase operation can be executed.
The superapp backend implements the RequestMidasPaymentGameItem API to verify whether the virtual item is purchasable and returns a valid response. The SAS SDK will then notify the superapp to continue with the payment process. The superapp needs to implement the following code logic:
Android:
Android client developers need to implement the proxy for MiniOpenApiProxy provided by the SDK and override the requestMidasPaymentGameItem method. In this method, they should complete the business logic for the mini game payment and return the payment result to the mini game via AsyncResult. Example code (Android-1):
@ProxyService(proxy = MiniOpenApiProxy.class)
public class MiniOpenApiProxyImpl extends MiniOpenApiProxy {

@Override
public void requestMidasPaymentGameItem(IMiniAppContext miniAppContext, JSONObject params, AsyncResult result) {
// call your custom payment implementation
boolean paySuccess = PaymentManagerV2.g().startMidasPayment(miniAppContext, params, result);
// notify payment result with AsynResult
if(paySuccess){
result.onReceiveResult(true,successData);
}else{
result.onReceiveResult(false,failedData);
}
}
}
iOS:
The superapp needs to implement the requestMidasPaymentGameItem proxy API to receive the parameters passed by the SDK and then request the superapp backend. Example code (iOS-1):
- (void)requestMidasPaymentGameItem:(TMFMiniAppInfo *)app params:(NSDictionary *)params completionHandler:(MACommonCallback)completionHandler{
[[TCMPPDemoPayManager sharedInstance] checkPreOrder:params appType:1 completionHandler:^(NSError * _Nullable err, PayResponseData * _Nullable result) {
if (!err) {
dispatch_async(dispatch_get_main_queue(), ^{
TCMPPDemoPaymentMethodsController *payMethodVC = [[TCMPPDemoPaymentMethodsController alloc]init];
payMethodVC.payResponseData = result;
payMethodVC.app = app;
[[[DebugInfo sharedInstance] topViewController].navigationController pushViewController:payMethodVC animated:NO];
payMethodVC.completeHandle = ^(NSDictionary * _Nullable result, NSError * _Nullable error) {
completionHandler(result,error);
};
});
}
}];
}
In the example code, TCMPPDemoPayManager is a utility class that encapsulates requests sent to the superapp backend.
When the user enters their payment authorization information on the payment page, the superapp will notify its backend that the mini game item direct purchase payment has been completed after validating the payment.
Delivery notification
After the mini game item direct purchase payment is completed, the superapp backend should proactively notify the SAS backend (openServer). For the API and parameters, see Mini game payment callback, and ensure that the response's returnCode is 0. If multiple retry attempts fail, an alert notification should be sent promptly.
Upon receiving the delivery notification, the SAS backend (openSever) will immediately call the callback URL provided during the order placement. If the mini game backend does not respond correctly, the SAS backend will continue to retry until a correct response is received.
Payment result confirmation
The superapp should implement the logic to callback the payment result to the SAS SDK upon successful payment.
On Android, the payment result executed by the superapp for the mini game is returned via the AsyncResult parameter of the requestMidasPaymentGameItem method. For details, see example code (Android-1).
TCMPPDemoPaymentMethodsController serves as the payment page. After the user completes the payment, the completeHandle is executed to pass the payment result back to the SDK via the completionHandler, as shown in the example code (iOS-1).
Subsequently, the SAS SDK will call the success callback function that was passed during the requestMidasPaymentGameItem function call at the time of order placement.
Strong recommendation: The mini game frontend should query the mini game backend again to confirm the payment result is genuinely completed.

Mini game virtual payment operations in the console

Once the technical solution is implemented in the superapp, the superapp admin needs to enable the payment feature in the console. After that, mini game developers can integrate virtual payment. For payment management, see: Payment Management.
After the superapp enables the payment feature, mini game developers can bind a merchant account in the console and add virtual items. Once the virtual items are released, they will be available for use in the mini game. For mini game developer operation guidelines, see:


Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback