Preliminary Preparation
For the HarmonyOS project to pass the review on the WeChat platform, a wx_app_id is required. It can generally be found through the platform. The process is omitted here.
Download Dependencies
First of all, we need to download the third-party library of WeChat to call relevant functions of WeChat, such as logging in, sharing with friends, sharing on Moments, etc.
Encapsulate the Callback Class
We can create a file and build a class.
This class is used for unified callbacks when we request WeChat functions. Some corresponding data will be returned. If we need to listen to a certain event, we can register here.
However, since unified callbacks are required, we can attach an identifier "state" when sending an event to distinguish the type of the callback event. The return value will also carry the identifier "state", and corresponding event handling can be carried out according to the "state" of the return value.
First, we need two arrays for storage.
// Used to store callback functions for WeChat request (Req) events.
// Both the key and the value are callback functions. Using a Map here makes it convenient to manage and delete callbacks.
onReqCallbacks: Map<
(req: wechatOpenSdk.BaseReq) => void,
(req: wechatOpenSdk.BaseReq) => void
> = new Map()
// Used to store callback functions for WeChat response (Resp) events.
// Both the key and the value are callback functions. Using a Map also makes it convenient to manage and delete callbacks.
onRespCallbacks: Map<
(resp: wechatOpenSdk.BaseResp) => void,
(resp: wechatOpenSdk.BaseResp) => void
> = new Map()
// Import all exports from the Tencent WeChat Open SDK and alias them as the wechatOpenSdk namespace
import * as wechatOpenSdk from "@tencent/wechat_open_sdk"
/**
* The WechatApiEventHandlerImpl class implements the wechatOpenSdk.WXApiEventHandler interface
* to handle request (Req) and response (Resp) events from the WeChat Open SDK,
* while managing event callback functions.
*/
class WechatApiEventHandlerImpl implements wechatOpenSdk.WXApiEventHandler {
/**
* Registers a callback function for WeChat request (Req) events
* @param on - The callback function to execute when a WeChat request is received,
* which takes a parameter of type BaseReq
*/
registerOnWXReqCallback(on: (req: wechatOpenSdk.BaseReq) => void) {
// Add the callback function to the onReqCallbacks map
this.onReqCallbacks.set(on, on)
}
/**
* Unregisters a callback function for WeChat request (Req) events
* @param on - The callback function to unregister, which takes a parameter of type BaseReq
*/
unregisterOnWXReqCallback(on: (req: wechatOpenSdk.BaseReq) => void) {
// Remove the specified callback function from the onReqCallbacks map
this.onReqCallbacks.delete(on)
}
/**
* Registers a callback function for WeChat response (Resp) events
* @param on - The callback function to execute when a WeChat response is received,
* which takes a parameter of type BaseResp
*/
registerOnWXRespCallback(on: (resp: wechatOpenSdk.BaseResp) => void) {
// Add the callback function to the onRespCallbacks map
this.onRespCallbacks.set(on, on)
}
/**
* Unregisters a callback function for WeChat response (Resp) events
* @param on - The callback function to unregister, which takes a parameter of type BaseResp
*/
unregisterOnWXRespCallback(on: (resp: wechatOpenSdk.BaseResp) => void) {
// Remove the specified callback function from the onRespCallbacks map
this.onRespCallbacks.delete(on)
}
/**
* This method is called when a WeChat request (Req) is received
* @param req - The received WeChat request object of type BaseReq
*/
onReq(req: wechatOpenSdk.BaseReq): void {
// Original comment: Log.i(kTag, "onReq:%s", JSON.stringify(req))
// Iterate over all callback functions in the onReqCallbacks map and execute them in sequence
this.onReqCallbacks.forEach((on) => {
on(req)
})
}
/**
* This method is called when a WeChat response (Resp) is received
* @param resp - The received WeChat response object of type BaseResp
*/
onResp(resp: wechatOpenSdk.BaseResp): void {
// Original comment: Log.i(kTag, "onResp:%s", JSON.stringify(resp))
// Iterate over all callback functions in the onRespCallbacks map and execute them in sequence
this.onRespCallbacks.forEach((on) => {
on(resp)
})
}
}
/**
* The WechatManager class manages WeChat-related operations such as image sharing and WeChat login.
*/
export class WechatManager {
/**
* UI ability context, used to provide application context information (optional property).
*/
context?: common.UIAbilityContext;
/**
* Creates a WeChat API instance using the WeChat app ID stored in the global variables.
*/
wxApi = wechatOpenSdk.WXAPIFactory.createWXAPI(GlobalVariable.WX_APP_ID);
/**
* Shares an image to a WeChat conversation.
* @param filePath - The local path of the image file to be shared.
*/
shareImage(filePath: string) {
// Create an image object
let imageObject = new wechatOpenSdk.WXImageObject();
// Set the URI of the image object using the file path
imageObject.uri = fileUri.getUriFromPath(filePath);
// Create a media message object
let mediaMessage = new wechatOpenSdk.WXMediaMessage();
// Attach the image object to the media message
mediaMessage.mediaObject = imageObject;
// Create a request object to send a message to WeChat
let req = new wechatOpenSdk.SendMessageToWXReq();
// Set the sharing scenario to a conversation
req.scene = wechatOpenSdk.SendMessageToWXReq.WXSceneSession;
// Attach the media message to the request
req.message = mediaMessage;
// Send the request via the WeChat API with the context
this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req);
}
/**
* Initiates a WeChat login request.
* @returns A Promise that resolves to true on success or rejects with false on failure.
*/
async login(): Promise<boolean> {
return new Promise(async (resolve, reject) => {
// Create an authorization request object
let req = new wechatOpenSdk.SendAuthReq();
// Set the authorization scope to retrieve user information
req.scope = "snsapi_userinfo";
// Generate a random UUID as the state parameter
const state = util.generateRandomUUID();
// Attach the state parameter to the request
req.state = state;
// Send the authorization request via the WeChat API
this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req);
// Register a callback for WeChat responses
wechatEventHandler.registerOnWXRespCallback(async (resp) => {
// Cast the response to a SendAuthResp object
const res = resp as wechatOpenSdk.SendAuthResp;
// Check if the state parameter matches and the error code indicates success
if (res.state === state && res.errCode === wechatOpenSdk.ErrCode.ERR_OK) {
// The WeChat login has been successfully initiated; proceed with subsequent operations
resolve(true);
} else {
// Reject the Promise if conditions are not met
reject(false);
}
});
});
}
}
Event Listening and Registration
Add an event within the lifecycle of the application window entry.
// Cold start mode. When the current application is launched by WeChat, listen for corresponding data.
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.handleWeChatCallIfNeed(want);
}
// Hot start mode. When returning to the current application from WeChat, listen for the need of corresponding responses.
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.handleWeChatCallIfNeed(want);
}
private handleWeChatCallIfNeed(want: Want) {
wechatManager.wxApi.handleWant(want, wechatEventHandler)
}
The version of the article and the code used is HarmonyOS 5.0.1 Release SDK.
Top comments (0)