Migrating User Data from WeChat Cloud Development to UniCloud
Context
Transitioning from a standalone WeChat Mini Program to a UniApp-based cross-platform solution necessitates a backend migration from WeChat Cloud Development to UniCloud. A primary challenge in this process involves transforming the user identification system from relying on WeChat's OpenID to UniCloud's native UID system.
Migration Strategy
1. WeChat Account Integration
The first step involves implementing a WeChat App login binding feature. It is important to note that this integration binds the WeChat Open Platform UnionID rather than the specific Mini Program OpenID directly.
async function linkWeChatAccount() {
try {
const loginRes = await uni.login({
provider: 'weixin',
onlyAuthorize: true
});
const authModule = uniCloud.importObject("uni-id-co", {
customUI: true
});
console.log("UniApp login result:", loginRes);
const result = await authModule.bindWeixin({ code: loginRes[1].code });
uni.showToast({
title: 'Authentication successful',
icon: 'none',
duration: 2000
});
handleLoginSuccess(result);
} catch (error) {
console.error("Authentication error:", error);
uni.showModal({
content: error.message,
confirmText: "Dismiss",
showCancel: false
});
} finally {
uni.hideLoading();
}
}
2. Identity Mapping and Data Retrieval
On the Mini Program client, users must authorize WeChat access to establish the relationship between the UnionID and the Mini Program OpenID. Subsequently, the UnionID is used as a key to retrieve the corresponding OpenID information from the legacy WeChat Cloud database.
3. Implementing Data Synchronization
Within the UniApp application, a synchronization mechanism must be established to query the legacy WeChat Cloud database and migrate the data into the UniCloud database.
Method A: HTTP API Access
The WeChat Cloud Database HTTP API can be utilized to read legacy data directly.
const requestData = {
"env": "legacy-wechat-env-id",
"query": "db.collection(\"legacy_table\").limit(10).get()"
};
const requestOptions = {
method: 'POST',
url: "https://api.weixin.qq.com/tcb/databasequery?access_token=" + accessToken,
data: requestData,
dataType: '',
header: {
"content-type": "application/"
}
};
Method B: Server-Side SDK Integration
A more robust approach involves creating a UniCloud function that uses the Tencent Cloud Node.js SDK to access the TCB (Tencent Cloud Base) database. This requires configuring a sub-account in the TCB console with specific policies (e.g., QcloudAccessForTCBRole) and obtaining the necessary secretId and secretKey.
'use strict';
const tcb = require('@cloudbase/node-sdk');
// Initialize TCB connection
const legacyApp = tcb.init({
secretId: 'your-secret-id',
secretKey: 'your-secret-key',
env: 'legacy-env-id'
});
const legacyDb = legacyApp.database();
const localDb = uniCloud.database();
const APP_ID = '__UNI__CUSTOM_APP_ID';
const PLATFORM = 'mp'; // Options: 'mp' (Mini Program), 'h5', 'web', 'app'
const fetchUserWeChatId = async (uid) => {
const userDoc = await localDb.collection('uni-id-users').doc(uid).get();
const userData = userDoc.data[0];
if (!userData) {
throw new Error('User record not found');
}
const weChatIdentifiers = userData.wx_openid || {};
// Retrieve the specific OpenID for the current platform/app
return weChatIdentifiers[`${PLATFORM}_${APP_ID}`] || weChatIdentifiers[PLATFORM];
};
exports.main = async (event, context) => {
console.log('Event payload:', event);
// Verify user token
const uniIDInstance = uniID.createInstance({ context: context });
const authPayload = await uniIDInstance.checkToken(event.uniIdToken);
const legacyOpenId = await fetchUserWeChatId(authPayload.uid);
console.log('Retrieved Legacy OpenID:', legacyOpenId);
// Query the legacy database
const queryResult = await legacyDb.collection("legacy_table").where({
_openid: legacyOpenId
})
.get();
console.log('Legacy query result:', queryResult);
return queryResult;
};
Troubleshooting Common Issues
Authentication Failures (SIGN_PARAM_INVALID)
Errors such as SIGN_PARAM_INVALID frequently occur due to missing permissions for actions like tcb:InvokeFunction or tcb:QueryDocument.
To resolve these authorization issues:
- Log in to the Tencent Cloud Console and navigate to Access Management (CAM).
- Create a policy or modify the user group/sub-account policy.
- Ensure the policy explicitly grants
tcb:InvokeFunctionandtcb:QueryDocumentpermissions. - Regenerate the access keys (
secretId/secretKey) after applying the policy. - Update the configuration in the UniCloud function with the new credentials.
Data Consistency Considerations
When implementing the synchronization logic, specific attention must be paid to maintaining data integrity. Ensuring that the synchronization point is correctly aligned between the legacy OpenID and the new UID is critical to prevent data loss or duplication during the migration process.