需求:用户在微信打开网页并使用微信分享后,链接显示自定义的title, description, 图片。
实现:
步骤一:绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
备注:登录后可在“开发者中心”查看对应的接口权限。
步骤二:引入JS文件
在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js
在angular6中如下图所示引用js文件:
步骤三: 新建一个weChatShare service, 内容如下
// 后台获取signature
public getWXJsInitConfig(url): any {
let wxSignUrl = environment.signatureApi + url;
return this.baseService.getNoHandleErr(wxSignUrl)
.then(data => { return data.data });
}
// 根据后台获取的数据注册config
public configWXJs(obj: any, jsApiList: Array<string>) {
wx.config({
debug: false,
appId: obj.appId,
timestamp: obj.timestamp + '',
nonceStr: obj.nonceStr,
signature: obj.signature,
jsApiList: jsApiList
});
}
// 对分享信息进行处理,并注册分享函数
public getShareDataAndReady(title, imgUrl, desc, slug) {
let shareTitle = title ? title : '自定义title';
let shareImg = imgUrl ? imgUrl : "默认图片";
let shareDesc = desc ? desc : '默认描述';
let link = location.href;
wx.ready(function () {
wx.onMenuShareAppMessage({ title: shareTitle, link: link , desc: shareDesc, imgUrl: shareImg }); // 分享微信
wx.onMenuShareTimeline({ title: shareTitle, link: link , desc: shareDesc, imgUrl: shareImg }); // 分享到朋友圈
wx.onMenuShareQQ({ title: shareTitle, link: link , desc: shareDesc, imgUrl: shareImg }); // 分享到QQ
});
}
在页面中使用:
//我的分享信息依赖this.siteConfig, 因此为了防止分享时分享信息没有获取到,在获取this.siteConfig后再调用分享的一系列函数和事件
this.siteConfig = await this.http.getSiteConfig();
// update share information
this.shareService.getWXJsInitConfig(encodeURIComponent(location.href.split('#')[0])).then(
data => {
this.shareService.configWXJs(data, [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ']);
this.shareService.getShareDataAndReady(this.siteConfig.home_share_title,
this.siteConfig.home_share_photo,
this.siteConfig.home_share_description,
"home");
}
);
注意事项:
- wx如果在ts文件中直接写会不识别报错, declare let wx: any; 这样声明一下就好了。
- 在iOS中分享的自定义图片名字不要有中文,否则会显示不出来。