# Instructions for using the open label
# Summary
WeChat Open tags are an extended set of tags provided by WeChat Official Platform for web developers.By using the WeChat open label, web developers can safely and conveniently use the capabilities of WeChat or the system to provide a better web experience for WeChat users.
This document is intended for web developers and describes how to use WeChat open tags and related notes.It should be noted that the WeChat open label has the lowest WeChat version requirements, the lowest system version requirements, and the lowest JS interface file version requirements.
- WeChat version requirements: 7.0.12 and above (if it is HongMeng system, WeChat version requirements: 1.0.3 and above)
- System version requirements: iOS 10.3 and above, Android 5.0 and above
- JS interface file: 1.6.0 above (for example: http://res.wx.qq.com/open/js/jweixin-1.6.0.js)
For scenarios that meet the requirements of WeChat or the minimum version of the system but still cannot use WeChat open tags,Thewx.config
permission verification is triggered when theWeixinOpenTagsError
event is notified to the developer below.Only WeChat can not be used to develop tags, and other functions of JS-SDK are not affected. Listening and backward compatibility can be achieved by the following methods:
document.addEventListener('WeixinOpenTagsError', function (e) {
console.error(e.detail.errMsg); // 无法使用开放标签的错误原因,需回退兼容。仅无法使用开放标签,JS-SDK其他功能不受影响
});
Based on currently known error scenarios, backwards compatibility recommendations are as follows:
- The iOS15 underlying WebKit interface has changed, WeChat version 8.0.8 below (excluding 8.0.8) can not use the open label, can guide users to upgrade the latest version of WeChat;
- The open label relies on the Web Components solution, and a few Android systems may not be supported because of the low version, which can guide users to upgrade the system firmware.
# Use steps
WeChat The use of open tags is similar to WeChat JS-SDK, and steps such as JS files need to be introduced. If it is a web page with Service Account identity, you need to bind a secure domain name, if it is using Weixin Mini Program cloud development A static website hosting Mini Program pages can be used directly without binding a secure domain name (i.e. skip "Step 1: binding secure domain names").
# 1. Binding Domain Name
Log in to WeChat public platform Go to the "function settings" of "Service Account Settings" and fill in "JS interface security domains."
# 2. Introduction of JS files
Introduce the following JS file on pages that need to call the JS interface: http://res.wx.qq.com/open/js/jweixin-1.6.0.js (https supported)
If you need to further improve service stability, when the above resources are not accessible, you can change access: http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (support https)
Note: Supports loading using the AMD / CMD standard module loading method.
# 3. Inject permissions through the config interface to validate the configuration and apply the required open labels
As with JS-SDK configuration, all pages that need to use open tags must first be injected with configuration information,And request the required open label via theopenTagList
field, otherwise it will not be available (the same url only needs to be called once).The application of the open label and the application of the JS interface are independent of each other, so they can be applied at the same time.
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印
appId: '', // 必填,服务号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [], // 必填,需要使用的JS接口列表
openTagList: [] // 可选,需要使用的开放标签列表,例如['wx-open-launch-app']
});
The signature algorithm can be found in the appendix of the JS-SDK documentation, and a list of all open tags can be found in Appendix 1 at the end of the article.
# 4. Processing successful validation via the ready interface
wx.ready(function () {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中
});
# 5. Handling failure validation via the error interface
wx.error(function (res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
});
# Instructions
All open tags can be used directly in the page just like normal HTML tags, without additional processing.
If the label used allows for a slot, because the style of the template in the slot is isolated from the page, be careful to define the style of your template in the slots.Slot templates and styles need to be wrapped with < script type = "text / wxtag-template" > < / script >.In addition, for named slots, you need to declare the slot name through the
slot 'attribute. The default slot in the tab slot below is the default slot and the slot name can not be declared.
For labeled events, detailed information is available atevent.detail
.Unless otherwise specified, the return values in the label event explaination below refer to the content inevent.detail
.
In addition, the following points need to be taken into account:
- Styles related to layout and positioning in a page, such as
position: fixed; top -100;
, etc., try not to write in the node of the slot template, please declare on the label or its parent node; - For pages with CSP requirements, whitelist
frame-src https://*.qq.com webcompt:
,You can use the open label normally on the page.
# Open labels
# Jump Weixin Mini Program: wx-open-launch-weapp
Used to provide a button on the page that can jump to the specified Weixin Mini Program. After using this tag, the user needs to click the tag button within the web page to jump to the Mini Program. H5 The scene value of opening an Mini Program through an open label is 1167.
# Open Objects
- A certified Service Account Web page with a service number binding to a "JS interface security domain" can use this tag to jump to any legitimate and compliant Weixin Mini Program.
- A verified non-personal subject's Weixin Mini Program and a static website hosted under a domain bound by [using a Mini Program cloud can use this tag to jump to any legally compliant Mini Program.
# Error prompts
If the following page appears on the jump, the page binding Service Account or Weixin Mini Program does not have permission, please check that the above open object conditions are met.
# attribute
name | Required to fill in | Default values | Remarks |
---|---|---|---|
appid | yes | Weixin Mini Program AppID Weixin Mini Program, that is, the Mini Program corresponding towx | |
username | no | The original Weixin Mini Program id for the required transition, the id corresponding to the Mini Program that starts withgh_ (When transitioning, the appid is given priority when there is AppID and the username is used without the appID) | |
path | no | Page path and parameters within Weixin Mini Program | |
env-version | no | release | The Weixin Mini Program version required to jump is the legal value: official release, developer, trial (supported WeChat version: iOS 8.0.18 and above, Android 8.0.19 and above) |
extra-data | no | Pass data as a JSON character string to Weixin Mini Program that you want to jump to.Mini Programs are available inApageonLaunch ,ApageonShow , etc.;MiniGame Available atwx.onAppShow ,wx.getLaunchOptionsSync (Supported versions: iOS 8.0.18 and above, Android 8.0.19 and above) |
# slot
name | Required to fill in | Default values | Remarks |
---|---|---|---|
default | yes | Jump button templates and styles |
# event
name | A bubble | Return value | Remarks |
---|---|---|---|
ready | no | When the tag is initialized, it can be clicked | |
launch | no | { appId: string, userName: string, path: string } | Triggered when the user clicks the jump button and acts on the confirmation window |
error | no | { errMsg: string, appId: string, userName: string, path: string } | An error occurred after the user clicked the jump button |
Note:error
Event return valueerrMsg
described below.
errMsg | Introductions |
---|---|
"launch:fail" | The jump failed |
# Use cases
<wx-open-launch-weapp
id="launch-btn"
appid="wx12345678"
path="pages/home/index?user=123&action=abc"
>
<script type="text/wxtag-template">
<style>.btn { padding: 12px }</style>
<button class="btn">打开小程序</button>
</script>
</wx-open-launch-weapp>
<script>
var btn = document.getElementById('launch-btn');
btn.addEventListener('launch', function (e) {
console.log('success');
});
btn.addEventListener('error', function (e) {
console.log('fail', e.detail);
});
</script>
# Jump APP: wx-open-launch-app
Used to provide a button on the page to jump to the specified app. Note: Android / HongMeng platform uses open tags to jump to App, App must access WeChat OpenSDK ,See the documentation for more details. [The Android WeChat OpenSDK Access Guide]]](https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/Android.html) [The HUAWEI WeChat OpenDK Access Guide]]]].
Additional note: 1 a real machine must be able to render the label; 2. The text chain cannot pull up the tag
# Open Objects
This feature is only available to certified Service Account and web pages with service numbers binding to the "JS interface security domain" can use this tag to jump to apps that meet certain criteria. Before using the tag, you first need to go to the WeChat open platform in Management Center - Official Account or Weixin Mini Program Details - API Information - Webpage Jump Mobile App - Association Settings to bind the app to be redirected. Detailed configuration rules reference document .
# attribute
name | Required to fill in | Default values | Remarks |
---|---|---|---|
appid | yes | AppID of Mobile App required to jump | |
extinfo | no | Additional information required for a jump |
Note: For theextinfo
attribute, used to carry additional information, the format is self-defined and processed by the jump App.For the messageExt field (LaunchFromWXReq.message.messageExt) in the iOS WeChat OpenSDK, or for the messageExtt field (ShowMessageFromWX.Req.Message.messageExtt) in the Android WeChat OpenSDK, see the document [App Gets Extinfo Data in Open Tag"] (https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/APP_GET_EXTINF.html).
# slot
name | Required to fill in | Default values | Remarks |
---|---|---|---|
default | yes | Jump button templates and styles |
# event
name | A bubble | Return value | Remarks |
---|---|---|---|
ready | no | When the tag is initialized, it can be clicked | |
launch | no | { appId: string, extInfo: string } | Triggered when the user clicks the jump button and acts on the confirmation window |
error | no | { errMsg: string, appId: string, extInfo: string } | An error occurred after the user clicked the jump button |
Note:error
Event return valueerrMsg
described below.
errMsg | Introductions |
---|---|
"launch:fail" | The current scenario does not support the jump, or the app is not installed on Android, or the user clicks Confirm on the pop-up on iOS but the app is not installed |
"launch:fail_check fail" | Verify that App redirect permission fails by confirming that the App ID is correctly bound and that the domain name is fully consistent (see ['In WeChat Web page redirect APP functionality]]](https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_H5_Launch_APP.html) ) |
# Use cases
<wx-open-launch-app
id="launch-btn"
appid="your-appid"
extinfo="your-extinfo"
>
<script type="text/wxtag-template">
<style>.btn { padding: 12px }</style>
<button class="btn">App内查看</button>
</script>
</wx-open-launch-app>
<script>
var btn = document.getElementById('launch-btn');
btn.addEventListener('launch', function (e) {
console.log('success');
});
btn.addEventListener('error', function (e) {
console.log('fail', e.detail);
});
</script>
# Service Account Subscription notification button: wx-open-subscribe
Service Account Provides the ability to set up subscription notifications on the web side.Call the client service number subscription notification interface to return the results of the user's subscription notifications operation.
Open object: Certified Service Account.Web pages under the service number binding "JS Interface Security Domain" can use this tag to activate subscriptions.
This is illustrated as follows:
# Note
- Open tags have a minimum WeChat version and system version requirements, and when the subscription button cannot be rendered, the developer must do the low-version processing themselves.
- A one-time template id and a permanent template id cannot be used at the same time.
- The developer tool supports clearing authorization and simulating subscriptions, which are currently fake data simulations. Please debug the actual results on the real machine.
# attribute
name | Required to fill in | Default values | Remarks |
---|---|---|---|
template | yes | Template id, multiple template id separated by commas |
# slot
name | Required to fill in | Default values | Remarks |
---|---|---|---|
default | yes | Subscribe button templates and styles | |
style | no | empty | Used to centrally define the styles needed for default slots |
# event
name | A bubble | Return value | Remarks |
---|---|---|---|
success | no | {errMsg: 'subscribe:ok', subscribeDetails: string} | Subscribe button operates a successful event |
error | no | {errMsg: string, errCode: string} | A failed event in the subscription button operation |
Success Event Attribute Dxplaination
attribute | type | Introductions |
---|---|---|
errMsg | string | The errMsg value is' subscribe: ok' when the button operation succeeds |
subscribeDetails | string | [TEMPLATE_ID] is the dynamic key, the template id. The values include: 'accept', 'reject', 'cancel','filter, 'accept' means that the user agrees to subscribe to the template message corresponding to the item's id,'reject' means the user refuses to subscribe the template messageCorresponding to the article's ids, 'cancel' means a user cancels a subscription to the template messaging corresponding to that item' id, and 'filter' means this template should be filtered by the background under the same title.For example: {errMsg: "subscribe: ok," subscribeDetails:"{"TenvU22BA1jCp4YHfYEpRuESXYReQyDuhs4vbdWA99I":"{\"status\":\"accept\"}"}"Indicates that the user agrees to subscribe to TenvU22BA1jCp4YHfYEpRuESXYReQyDuhs4vbdWA99I this message. |
Error Event Property Dxplaination
attribute | type | Introductions |
---|---|---|
errMsg | string | Subscription button invocation failed error message |
errCode | string | Subscription button invocation failed error code |
Note:error
event returnserrMsg
anderreCode
. The instructions are as follows.
errCode | errMsg | Introductions |
---|---|---|
10001 | template can't be empty | The parameter passed to space. |
10002 | Request list fail | Network problem, request message list failed |
10003 | Request subscribe fail | Network problem, subscription request sent failed |
10004 | Invalid template id | Error in parameter type |
20001 | No template data return, verify the template id exist | There is no template data, usually because the template ID does not exist or does not correspond to the template type. |
20002 | Templates type must be same | Template message types are both one-time and permanent |
20003 | Templates count out of max bounds | The number of template messages exceeds the limit |
20004 | The main switch is switched off | The user turned off the main switch and could not subscribe |
20005 | This mini program was banned from subscribing messages | Service Account Banned |
# Use cases
<wx-open-subscribe template="TenvU22BA1jCp4YHfYEpRuESXYReQyDuhs4vbdWA99I" id="subscribe-btn">
<script type="text/wxtag-template" slot="style">
<style>
.subscribe-btn {
color: #fff;
background-color: #07c160;
}
</style>
</script>
<script type="text/wxtag-template">
<button class="subscribe-btn">
一次性模版消息订阅
</button>
</script>
</wx-open-subscribe>
<script>
var btn = document.getElementById('subscribe-btn');
btn.addEventListener('success', function (e) {
console.log('success', e.detail);
});
btn.addEventListener('error',function (e) {
console.log('fail', e.detail);
});
</script>
# Audio Playback: wx-open-audio
Extended audio tag for access to the WeChat floating window broadcaster.
# Open Objects
This feature is only available to certified Service Account and web pages under the service number binding "JS Interface Security Domain" can use this tag for floating-window audio playback.
# attribute
name | Required to fill in | Default values | Remarks |
---|---|---|---|
src | yes | - | Set up audio playback links |
title | no | "unknown" | Set the audio name |
episode | no | "unknown" | Set album name |
singer | no | "unknown" | Set the name of the singer |
cover | no | "" | Set the album cover |
<wx-open-audio
title="别找我麻烦"
singer="蔡健雅"
episode="说到爱"
src="http://URL地址/.mp3"
cover="http://URL地址/xxx.jpg"
></wx-open-audio>
# slot
The view of the tag can be understood as a play button and therefore has the following slot:
name | Required to fill in | Default values | Remarks |
---|---|---|---|
default | no | - | Play button default view for when the audio is not playing, if not, the default WeChat Audio Play button (40px * 40px) |
playing | no | - | Used to display audio while playing, if not, default slot view or WeChat audio play button |
style | no | empty | Used to centrally define styles needed for default slots and playing slots |
<wx-open-audio src="http://URL地址/.mp3">
<script type="text/wxtag-template">
<div class="playBackground"></div>
</script>
<script type="text/wxtag-template" slot="playing">
<div class="pauseBackground"></div>
</script>
<script type="text/wxtag-template" slot="style">
<style>
.playBackground {
width: 60px;
height: 64px;
background: url("xxx");
background-repeat: no-repeat;
background-size: 100%;
cursor: pointer;
}
.pauseBackground {
width: 60px;
height: 64px;
background: url("xxx");
background-repeat: no-repeat;
background-size: 100%;
cursor: pointer;
}
</style>
</script>
</wx-open-audio>
# Instance properties
name | Remarks |
---|---|
src | Get and set up audio playback links |
title | Get and set audio names |
episode | Get and set album name |
singer | Get and set a singer name |
cover | Get and set the album cover |
ended | Whether the audio is currently finished playback |
paused | Get audio is currently paused |
duration | Get audio length, per second |
readyState | Get the audio current ready state, meaning aligned W3C standard , but only 1 / 2 / 4 of three states |
currentTime | Get and set the playback progress per second (% * The settings only take effect when the audio is playing in the background or when it is paused in the background) |
playbackRate | WeChat 7.0.15 and above supports getting and setting the playback rate in the range 0 to 2 (\ * the setting only takes effect when the audio is playing in the background) |
error | Get audio-related error information |
Note:error
Attributes are described below.
error | Introductions |
---|---|
"play:fail" | Failed to call the play method |
"pause:fail" | Failed to call pause method |
"seek:fail" | Failed to set currentTime |
"ratechange:fail" | Failed to set playbackRate |
//
const audio = document.getElementById('audio');
console.log(audio.src);
console.log(audio.title);
console.log(audio.episode);
console.log(audio.singer);
console.log(audio.cover);
console.log(audio.error);
console.log(audio.ended);
console.log(audio.paused);
console.log(audio.duration);
console.log(audio.readyState);
console.log(audio.currentTime);
console.log(audio.playbackRate);
audio.src = 'http://URL地址/.mp3'
audio.title = '别找我麻烦'
audio.episode = '说到爱'
audio.singer = '蔡健雅'
audio.cover = 'http://URL地址/xxx.jpg'
audio.currentTime = 100;
audio.playbackRate = 1.0;
# Example method
name | Remarks |
---|---|
load | Reload the audio |
play | Playing audio. For user experience reasons, the call is only allowed after the user first clicks to trigger playback |
pause | Pause playback of audio |
//
const audio = document.getElementById('audio');
audio.load();
audio.play();
audio.pause();
# event
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
ready | no | no | Audio tags are initialized |
//
const audio = document.getElementById('audio');
audio.addEventListener('ready', function (event) {
// 标签初始化完成
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
durationchange/loadedmetadata | no | no | Pull audio meta information successfully |
//
const audio = document.getElementById('audio');
audio.addEventListener('durationchange', function (event) {
// 获取到音频长度
const state = event.detail;
console.log(state.duration);
});
audio.addEventListener('loadedmetadata', function (event) {
// 音频meta信息只有长度,因此loadedmetadata会接着马上触发
const state = event.detail;
console.log(state.duration);
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
canplay | no | no | Audio can be played |
//
const audio = document.getElementById('audio');
audio.addEventListener('canplay', function (event) {
// 可随时播放
const state = event.detail;
console.log(state.duration);
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
play | no | no | The audio begins to play |
//
const audio = document.getElementById('audio');
audio.addEventListener('play', function (event) {
// 开始播放
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
pause | no | no | Audio stops playing |
//
const audio = document.getElementById('audio');
audio.addEventListener('pause', function (event) {
// 停止播放
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
timeupdate | no | no | Audio-related information is synchronized while playing |
//
const audio = document.getElementById('audio');
audio.addEventListener('timeupdate', function (event) {
const state = event.detail;
console.log(state.src); // 当前音频来源
console.log(state.title); // 当前音频标题
console.log(state.episode); // 当前专辑名称
console.log(state.singer); // 当前歌手名称
console.log(state.cover); // 当前专辑封面
console.log(state.playState); // 播放状态,'playing' | 'pause' | 'seeked'
console.log(state.paused); // 是否暂停
console.log(state.buffered); // 已缓冲位置,单位秒
console.log(state.currentTime); // 当前播放位置,单位秒
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
seeked | no | no | After setting currentTime, the audio playback position change is complete |
//
const audio = document.getElementById('audio');
audio.addEventListener('seeked', function (event) {
// 播放位置变更完成
const state = event.detail;
console.log(state.currentTime); // 变更后播放位置,单位秒
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
ratechange | no | no | When you set the playbackRate, the audio playback rate changes complete (WeChat 7.0.15 and above) |
//
const audio = document.getElementById('audio');
audio.addEventListener('ratechange', function (event) {
// 播放位置变更完成
const state = event.detail;
console.log(state.playbackRate); // 变更后播放速率
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
ended | no | no | Audio playback ends |
//
const audio = document.getElementById('audio');
audio.addEventListener('ended', function (event) {
// 播放结束
});
name | A bubble | Cancellation is possible | Remarks |
---|---|---|---|
error | no | no | An error occurred during the audio loading, playback or operation |
//
const audio = document.getElementById('audio');
audio.addEventListener('error', function (event) {
// 发生错误
const error = event.detail;
console.log(error.errMsg);
// 1. play:fail(调用play方法失败)
// 2. pause:fail(调用pause方法失败)
// 3. seek:fail(设置currentTime失败)
// 4. ratechange:fail(设置playbackRate失败)
});
# Used in frameworks such as Vue, React, etc.
The contents and styles of the slot template are isolated from the home page, and changing the contents and styling in the slot template in a data-driven manner will not be updated.
# Use in Vue
Open tags are custom tags, and Vue will give warnings about unknown tags by configuringVue.config.ignoredElements
To ignore Vue's open label checks.
<wx-open-audio
:title="title"
src="http://URL地址/.mp3"
@canplay="canplay"
@pause="pause"
@seeked="seeked"
>
<script type="text/wxtag-template">
<button>播放</button>
</script>
</wx-open-audio>
# Use in React
Because it is not compatible with synthetic events, native events need to be bound.
function Audio() {
const audio = useRef(null);
useEffect(() => {
const canplay = () => {};
const pause = () => {};
const seeked = () => {};
audio.current.addEventListener('canplay', canplay);
audio.current.addEventListener('pause', pause);
audio.current.addEventListener('seeked', seeked);
return () => {
audio.current.removeEventListener('canplay', canplay);
audio.current.removeEventListener('pause', pause);
audio.current.removeEventListener('seeked', seeked);
};
}, []);
return (
<wx-open-audio
ref={audio}
title="别找我麻烦"
src="http://URL地址/.mp3"
>
<script type="text/wxtag-template">
<button>播放</button>
</script>
</wx-open-audio>
);
}
# Appendix - List of all open labels
<wx-open-launch-weapp\>
<wx-open-launch-app\>
<wx-open-subscribe\>
<wx-open-audio\>
# App gets extinfo data in open label
This chapter mainly introduces the H5 page in WeChat through the user click WeChat open label "jump App, App side to get the open label in the way of extinfo field.
# Access WeChat OpenSDK
To access the data that the app carries when invoking it, the app first needs to access WeChat OpenSDK.
!!! Note: The AppIDs referred to in this document refer to the AppID of the App that is applied for when accessing OpenSDK.
WeChat OpenSDK related documents: iOS :
Android :
Hung Meng
# The app side gets the extinfo data passed by the open label
Please ensure that you have followed the above steps to access OpenSDK and verify successful access
# IOS Sample Code
Override the associated methods for AppDelegate.m or SceneDelegate (refer to the access documentation in the steps above):
//AppDelegate.m
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
//开启SDK Log
[WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
NSLog(@"WeChatSDK: %@", log);
}];
// 在调用WXApi的handle方法前,须先调用registerApp注册。ret为注册结果,若注册失败,请根据sdk的log排查原因
BOOL ret = [WXApi registerApp:APP_ID universalLink:UNIVERSAL_LINK];
if ([WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]) {
/// handled by OpenSDK
}
return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler
{
//开启SDK Log
[WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
NSLog(@"WeChatSDK: %@", log);
}];
// 在调用WXApi的handle方法前,须先调用registerApp注册。ret为注册结果,若注册失败,请根据sdk的log排查原因
BOOL ret = [WXApi registerApp:APP_ID universalLink:UNIVERSAL_LINK];
if ([WXApi handleOpenUniversalLink:userActivity delegate:[WXApiManager sharedManager]) {
/// handled by OpenSDK
}
return YES;
}
Override the onReq method of WXApiDelegate:
/*! @brief 收到一个来自微信的请求,第三方应用程序处理完后调用sendResp向微信发送结果
*
* 收到一个来自微信的请求,异步处理完成后必须调用sendResp发送处理结果给微信。
* 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
* @param req 具体请求内容,是自动释放的
*/
- (void)onReq:(BaseReq*)req
{
//获取开放标签传递的extinfo数据逻辑
if ([req isKindOfClass:[LaunchFromWXReq class]])
{
WXMediaMessage *msg = req.message;
NSString *openID = req.openID;
NSString *extinfo = req.msg.messageExt;
// handle...
}
}
# Android Sample Code
Reinventing the OnReq method of IWXAPIEventHandler to get the extInfo
public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
private IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//初始化和注册
IWXAPI api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
Intent intent = getIntent();
api.handleIntent(intent, this)
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
api.handleIntent(intent, this);
}
/**
* 从微信启动App
* @param req
*/
@Override
public void onReq(BaseReq req) {
//获取开放标签传递的extinfo数据逻辑
if(req.getType() == ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX && req instanceof ShowMessageFromWX.Req) {
ShowMessageFromWX.Req showReq = (ShowMessageFromWX.Req) req;
WXMediaMessage mediaMsg = showReq.message;
String extInfo = mediaMsg.messageExt;
//Handle...
}
}
@Override
public void onResp(BaseResp resp) {
}
}
# Example code for hongmeng
To configure and WeChat the action of the convention, in thesrc / main / module.json5
of the App module, find the entry ability and configureactionwxentity.action.open
:
{
"module": {
"type": "entry",
"abilities": [
{
"name": "DemoEntryAbility",
"srcEntry": "./ets/entryability/DemoEntryAbility.ets",
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home",
"wxentity.action.open" // 微信拉起App时会用该action,需接入方配置
]
}
]
}
]
}
}
Override the associated method ofwxopensdk.WXApiEventHandler
(parameter access document in the above step):
/**
* 从微信启动App
*
* @param req
*/
onReq(req: wxopensdk.BaseReq): void {
if (req instanceof wxopensdk.LaunchFromWXReq) {
// //获取开放标签传递的extinfo数据逻辑
let messageExt = req.message?.messageExt
//Handle...
}
}