【HarmonyOS 5】Integrating WeChat Sharing into HarmonyOS Applications

GeorgeGcs
• 阅读 2
  1. Download HarmonyOS WeChat Open SDK and Demo

  2. 1 WeChat_Open_SDK Insert image description here Click to download @tencent/wechat_open_sdk(V1.0.7).

  3. 2 Official Demo Download Insert image description here Click to download OpenSDK-1.0.0.zip. Insert image description here

  4. Run the Demo Project After syncing the configuration of the WeChat demo project and enabling automatic signing, it runs successfully with the following effect: Insert image description here
    The WeChat sharing page (triggered by the "Send Message" button) supports two sharing types: text and images. Image sharing includes three methods: network image URI, album selection, and local image data: Insert image description here
    The sharing logic is implemented in SendMessage.ets. Without configuring the APPID, clicking "Send XX Message" redirects to WeChat but shows an error: Insert image description here
    Configuration Steps:

  5. Update Constants.ets with your app's information.

  6. Register your HarmonyOS app on the WeChat Open Platform, configuring the package name and other details. (Note: WeChat requires a registered app ID; no test ID is provided for preview.) Insert image description here

  7. Integrate Sharing Functionality

  8. 1 Install SDK Dependencies Use the latest SDK version in your project: Insert image description here
    "dependencies": { "@tencent/wechat_open_sdk": "1.0.3" } Insert image description here
    Current Limitations:
    ● Only sharing to chat sessions is supported; sharing to Moments is under development.

3.2 Text Sharing (Refer to SendMessage.ets) import * as wxopensdk from '@tencent/wechat_open_sdk';

onClickSendText = async () => { // Create text object const textObject = new wxopensdk.WXTextObject(); textObject.text = kTextMessage;

// Wrap in media message const mediaMessage = new wxopensdk.WXMediaMessage(); mediaMessage.mediaObject = textObject;

// Send request const req = new wxopensdk.SendMessageToWXReq(); req.scene = wxopensdk.SendMessageToWXReq.WXSceneSession; req.message = mediaMessage;

const finished = await this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req); console.log("send request finished: ", finished); }

3.3 Image Sharing (Refer to SendMessage.ets) (1) Share Image by Network URL import * as wxopensdk from '@tencent/wechat_open_sdk';

onClickSendImageByUrl = () => { const imageUrl = "https://img.tukuppt.com/photo-big/00/10/77/619619681755c5463.jpg";

// Download image to app sandbox this.downloadImageWithUrl(imageUrl, async (imageData) => { let file: fileIo.File | undefined; const filePath = getContext(this).filesDir + /original-${Date.now()}.jpg; file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); fileIo.writeSync(file.fd, imageData); fileIo.closeSync(file);

// Create image object with local path
const imageObject = new wxopensdk.WXImageObject();
imageObject.uri = fileUri.getUriFromPath(filePath);

// Wrap and send
const mediaMessage = new wxopensdk.WXMediaMessage();
mediaMessage.mediaObject = imageObject;

const req = new wxopensdk.SendMessageToWXReq();
req.scene = wxopensdk.SendMessageToWXReq.WXSceneSession;
req.message = mediaMessage;

this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req);

}); }

downloadImageWithUrl(url: string, completion: (imageData: ArrayBuffer) => void) { http.createHttp().request(url, (error: BusinessError, data: http.HttpResponse) => { if (error || data.responseCode !== 200) return; completion(data.result as ArrayBuffer); }); } (2) Share Image from Album onClickSendImageByAlbum = async () => { const imageObject = new wxopensdk.WXImageObject(); imageObject.uri = await this.getPictureUriFromAlbum();

const mediaMessage = new wxopensdk.WXMediaMessage(); mediaMessage.mediaObject = imageObject;

const req = new wxopensdk.SendMessageToWXReq(); req.scene = this.currentScene; req.message = mediaMessage;

this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req); }

async getPictureUriFromAlbum(): Promise { const options = new photoAccessHelper.PhotoSelectOptions(); options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; options.maxSelectNumber = 1;

const picker = new photoAccessHelper.PhotoViewPicker(); const result = await picker.select(options); const albumPath = result.photoUris[0];

const context = getContext(this) as common.UIAbilityContext; let file: fileIo.File | undefined; file = fileIo.openSync(albumPath, fileIo.OpenMode.READ_ONLY);

const timeStamp = Date.now(); fileIo.copyFileSync(file.fd, context.filesDir + /original-${timeStamp}.jpg); fileIo.closeSync(file);

const filePath = context.filesDir + /original-${timeStamp}.jpg; return fileUri.getUriFromPath(filePath); } (3) Share Image from App Resources onClickSendImageByData = async () => { // Get image from resources and convert to PixelMap const resourceManager = getContext(this).resourceManager; const imageArray = await resourceManager.getMediaContent($r('app.media.test0')); const pixelBuffer = imageArray.buffer as ArrayBuffer; const imageResource = image.createImageSource(pixelBuffer); const opts: image.DecodingOptions = { editable: true }; const pixelMap = await imageResource.createPixelMap(opts);

// Compress and convert to ArrayBuffer const packer = image.createImagePacker(); const packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 }; await packer.packing(pixelMap, packOpts).then((data: ArrayBuffer) => { // Create image object with base64 data const imageObject = new wxopensdk.WXImageObject(); const buf = buffer.from(data); imageObject.imageData = buf.toString('base64', 0, buf.length);

// Wrap and send
const mediaMessage = new wxopensdk.WXMediaMessage();
mediaMessage.mediaObject = imageObject;

const req = new wxopensdk.SendMessageToWXReq();
req.scene = this.currentScene;
req.message = mediaMessage;

this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req);

}); } Note: WeChat has a 100KB limit for image sharing. Using URI-based sharing is recommended to avoid manual compression.

3.4 New Features in Version 1.0.7 (1) Share Webpage // Create webpage object const webpageObject = new wxopensdk.WXWebpageObject(); webpageObject.webpageUrl = "http://www.qq.com";

// Wrap in media message const mediaMessage = new wxopensdk.WXMediaMessage(); mediaMessage.mediaObject = webpageObject; mediaMessage.title = "Test Webpage Link"; mediaMessage.description = "Test webpage summary";

// Set thumbnail const thumbData = await getContext(this).resourceManager.getMediaContent($r("app.media.thumb_img")); const thumbPixel = image.createImageSource(thumbData.buffer).createPixelMapSync(); const thumbBuffer = await image.createImagePacker().packToData(thumbPixel, { format: "image/png", quality: 100 }); mediaMessage.thumbData = new Uint8Array(thumbBuffer);

// Send request const req = new wxopensdk.SendMessageToWXReq(); req.callbackAbility = kDemoEntryAbility; req.scene = wxopensdk.SendMessageToWXReq.WXSceneSession; req.message = mediaMessage;

this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req); (2) Share Mini Program // Create mini program object const miniProgramObject = new wxopensdk.WXMiniProgramObject(); miniProgramObject.userName = "gh_ac032d0848a9"; // Replace with your mini program's username miniProgramObject.path = "pages/Home/Home"; miniProgramObject.miniprogramType = wxopensdk.WXMiniProgramType.RELEASE;

// Wrap in media message const mediaMessage = new wxopensdk.WXMediaMessage(); mediaMessage.mediaObject = miniProgramObject; mediaMessage.title = "Test Mini Program Share Title"; mediaMessage.description = "Mini program share description";

// Set thumbnail const thumbData = await getContext(this).resourceManager.getMediaContent($r("app.media.thumb_img2")); const thumbPixel = image.createImageSource(thumbData.buffer).createPixelMapSync(); const thumbBuffer = await image.createImagePacker().packToData(thumbPixel, { format: "image/png", quality: 100 }); mediaMessage.thumbData = new Uint8Array(thumbBuffer);

// Send request const req = new wxopensdk.SendMessageToWXReq(); req.callbackAbility = kDemoEntryAbility; req.scene = wxopensdk.SendMessageToWXReq.WXSceneSession; req.message = mediaMessage;

this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req); Note: Do not use the demo's userName for mini program sharing—use your target mini program's configuration instead.

点赞
收藏
评论区
推荐文章
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
GeorgeGcs GeorgeGcs
19小时前
【 HarmonyOS 5 入门系列 】鸿蒙HarmonyOS示例项目讲解
【HarmonyOS5入门系列】鸿蒙HarmonyOS示例项目讲解\鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言:移动开发声明式UI框架的技术变革在移动操作系统的发展历程中,UI开发模式经历了从命令式到声明式的重大变革。根据
GeorgeGcs GeorgeGcs
19小时前
【HarmonyOS 5】AttributeModifier和AttributeUpdater区别详解
【HarmonyOS5】AttributeModifier和AttributeUpdater区别详解\鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、AttributeModifier和AttributeUpdater的定义和作用1
GeorgeGcs GeorgeGcs
8小时前
【HarmonyOS 5】Integrating Weibo Sharing into HarmonyOS Applications
●OfficialSDKWebsite:https://open.weibo.com/wiki/SDK●DownloadtheHarmonyOSSDKdemoprojectpackage.Aftercompletion,thecompressedfiles
GeorgeGcs
GeorgeGcs
Lv1
男 · 金融头部企业 · 鸿蒙应用架构师
HarmonyOS认证创作先锋,华为HDE专家,鸿蒙讲师,作者。目前任职鸿蒙应用架构师。 历经腾讯,宝马,研究所,金融。 待过私企,外企,央企。 深耕大应用开发领域十年。 AAE,Harmony(OpenHarmony\HarmonyOS),MAE(Android\IOS),FE(H5\Vue\RN)。
文章
56
粉丝
1
获赞
2