【HarmonyOS NEXT】鸿蒙应用接入微信分享
一、下载鸿蒙版微信开放SDK和示例DEMO
1.WeChat_Open_SDK:
点击跳转@tencent/wechat_open_sdk(V1.0.7)
2.官方示例DEMO下载
点击下载OpenSDK-1.0.0.zip
二、运行示例项目
微信的示例项目进行配置同步后,设置自动签名就可以直接运行成功,效果如下:
可以看到微信分享相关在,发送消息按钮,跳转到的页面中,共有两种分享形式,文本和图片。图片又分为网络图片uri,相册选图,和image发送三种:
分享页面实现都在SendMessage中,在没有配置APPID的情况下,点击发送XX消息,会跳转到微信,但是会提示第三方应用信息校验失败:
需要在Constants.ets中进行配置:
微信开放平台需要注册你的鸿蒙应用,配置包名等信息。微信最麻烦的就是这个,没有提供一个测试id进行效果查看,只能先去注册你的应用。点击鸿蒙应用手册
三、copy分享相关代码进行接入
1.安装SDK依赖:
sdk版本以三方库的最新版本为准:
"dependencies": {
"@tencent/wechat_open_sdk": "1.0.3"
}
分享的目标场景,目前仅支持分享到会话,分享到朋友圈功能还在开发中。
分享的目标场景,目前仅支持分享到会话,分享到朋友圈功能还在开发中。
分享的目标场景,目前仅支持分享到会话,分享到朋友圈功能还在开发中。
2.参考SendMessage.ets中的代码,copy【文本分享】相关代码:
import * as wxopensdk from '@tencent/wechat_open_sdk';
onClickSendText = async ()=>{
// 创建文本分享容器对象,并且赋值文本
let textObject = new wxopensdk.WXTextObject;
textObject.text = kTextMessage;
// 放到消息对象包裹里
let mediaMessage = new wxopensdk.WXMediaMessage();
mediaMessage.mediaObject = textObject;
// 发送包裹,根据返回值判断成功与否
let req = new wxopensdk.SendMessageToWXReq();
req.scene = wxopensdk.SendMessageToWXReq.WXSceneSession;
req.message = mediaMessage
let finished = await this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req)
console.log("send request finished: ", finished)
}
3.参考SendMessage.ets中的代码,copy【图片分享】相关代码:
(1)用网络图片发送Image消息(uri)
import * as wxopensdk from '@tencent/wechat_open_sdk';
onClickSendImageByUrl = ()=>{
let imageUrl = "https://img.tukuppt.com/photo-big/00/10/77/619619681755c5463.jpg"
// 网络图片的url地址,下载到本地应用沙箱
this.downloadImageWithUrl(imageUrl, async (imageData) => {
let file: fileIo.File | undefined;
let 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);
// 创建图片分享容器对象,并且赋值图片本地地址
let imageObject = new wxopensdk.WXImageObject
imageObject.uri = fileUri.getUriFromPath(filePath);
// 放到消息对象包裹里
let mediaMessage = new wxopensdk.WXMediaMessage()
mediaMessage.mediaObject = imageObject
// 放到消息对象包裹里
let 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)从相册中选择图片发送Image消息
onClickSendImageByAlbum = async ()=>{
let imageObject = new wxopensdk.WXImageObject
imageObject.uri = await this.getPictureUriFromAlbum()
let mediaMessage = new wxopensdk.WXMediaMessage()
mediaMessage.mediaObject = imageObject
let req = new wxopensdk.SendMessageToWXReq()
req.scene = this.currentScene
req.message = mediaMessage
this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req)
}
async getPictureUriFromAlbum(): Promise<string> {
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
let albumPath = photoSelectResult.photoUris[0];
let context = getContext(this) as common.UIAbilityContext;
let file: fileIo.File | undefined;
file = fileIo.openSync(albumPath, fileIo.OpenMode.READ_ONLY);
let timeStamp = Date.now();
fileIo.copyFileSync(file.fd, context.filesDir + `/original-${timeStamp}.jpg`);
fileIo.closeSync(file);
let filePath = context.filesDir + `/original-${timeStamp}.jpg`;
return fileUri.getUriFromPath(filePath);
}
(3)发送Image消息(data) 【应用资源文件夹内的图片资源】
onClickSendImageByData = async ()=>{
// 本地资源管理工具
let resourceManager = getContext(this).resourceManager
// 获取资源文件夹中的图片,转化为pixelMap
let imageArray = await resourceManager.getMediaContent($r('app.media.test0'));
let pixelBuffer = imageArray.buffer as ArrayBuffer;
let imageResource = image.createImageSource(pixelBuffer);
let opts: image.DecodingOptions = { editable: true }
let pixelMap = await imageResource.createPixelMap(opts);
// 压缩图片,获取ArrayBuffer
const imagePackerApi: image.ImagePacker = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 };
imagePackerApi.packing(pixelMap, packOpts).then((data: ArrayBuffer) => {
// 老规矩三件套,创建对象,填充,发射
let imageObject = new wxopensdk.WXImageObject
let buf: buffer.Buffer = buffer.from(data);
imageObject.imageData = buf.toString('base64', 0, buf.length);
let mediaMessage = new wxopensdk.WXMediaMessage()
mediaMessage.mediaObject = imageObject
let req = new wxopensdk.SendMessageToWXReq()
req.scene = this.currentScene
req.message = mediaMessage
this.wxApi.sendReq(getContext(this) as common.UIAbilityContext, req)
})
}
注意
微信分享 图片大小有限制,需要小于100kb。所以最好使用Uri的形式进行图片分享。要不然你得处理图片压缩。
3. 目前版本1.0.7,新增微信分享网页和分享小程序:
(1) 微信分享网页
const webpageObject = new wxopensdk.WXWebpageObject()
webpageObject.webpageUrl = "http://www.qq.com"
const mediaMessage = new wxopensdk.WXMediaMessage()
mediaMessage.mediaObject = webpageObject
mediaMessage.title = "测试网页链接"
mediaMessage.description = "测试网页摘要"
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)
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) 微信分享小程序
const miniProgramObject = new wxopensdk.WXMiniProgramObject()
miniProgramObject.userName = "gh_ac032d0848a9"
miniProgramObject.path = "pages/Home/Home"
miniProgramObject.miniprogramType = wxopensdk.WXMiniProgramType.RELEASE
const mediaMessage = new wxopensdk.WXMediaMessage()
mediaMessage.mediaObject = miniProgramObject
mediaMessage.title = "测试分享小程序Title"
mediaMessage.description = "分享小程序描述信息"
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)
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)
注意
微信分享小程序 不要使用示例的userName,否则会导致分享失败。请使用自己的目标小程序配置信息。