公众号配置
AppId以及AppSecret
这里注意需要的 AppId以及AppSecret 是一个公众号的AppId以及AppSecret而非小程序的。
先登录公众号平台获取(注意这里需要时公众号而非小程序)
- 设置与开发->开发接口管理->成为开发者操作之后,查看基本配置
- 在账号开发信息中获取 AppID & AppSecret
测试账号
如果没有自己的公众号的话。微信官方提供的测试账号:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
配置IP白名单
在公众号平台中 设置与开发->安全中心->ip白名单设置。这里需要把IP的白名单设置好,本机测试可以使用ngrok,获取了ngrok的几个动态ip都加到白名单里面去了,但我试了一下好像不管用,就直接使用了一个阿里云的服务器。
JS接口安全域名&验证文件
在公众号后台中的 设置与开发->账号设置->功能设置->JS接口安全域名中添加相关的域名
并把弹框中的MP_xx.txt的文件下载,然后在node服务器中启动一个静态文件服务器,保障在配置的域名后面可以直接访问到这个文件
比如: https://chshuyuan-dev.xhceyu.com/MP_verify_iyWE8fX3O0kuSy7o.txt 可以直接访问到这个文件
配置安全验证文件
这里是使用了宝塔来配置
要保证在这个域名下可以访问到这个验证文件
生成配置参数
配置好之后可以使用前端请求服务端,服务端先根据AppId以及AppSecret生成对应的access_token再用access_token生成对应的jsapi_ticket(票据)再根据一些列的参数生成配置参数
获取 accesToken
主要是根据公众号appId和appSecret获取accesToken
// 需要鉴权
async getAccessToken() {
try {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wechatPublicAppId}&secret=${wechatPublicAppSecret}`;
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(error);
return null;
}
}
获取jsapi_ticket
主要是根据accesToken 再获取票据jsapi_ticket
// 获取微信公众平台jsapi_ticket
async getJsapiTicket() {
try {
const accessToken = await this.getAccessToken();
const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken.access_token}&type=jsapi`;
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(error);
return null;
}
}
生成配置参数
主要是票据和一些列参数生成对应的wxConfig需要的参数
async getWxConfig(url: string) {
try {
const jsapiTicket = await this.getJsapiTicket();
const noncestr = Math.random().toString(36).substr(2, 15);
const timestamp = Math.floor(Date.now() / 1000);
// 解码URL
const decodedUrl = decodeURIComponent(url);
const str = `jsapi_ticket=${jsapiTicket.ticket}&noncestr=${noncestr}×tamp=${timestamp}&url=${decodedUrl}`;
const signature = createHash('sha1').update(str).digest('hex');
return {
appId: wechatPublicAppId,
timestamp,
nonceStr: noncestr,
signature,
url,
};
} catch (error) {
console.error(error);
return null;
}
}
这里注意URL参数是从前端传过来的,也就是之前在公众号安全域名中添加过的
这里实际上传递的是前面公众号配置添加过的chshuyuan-dev.xhceyu.com/
开发者工具
使用Chrome没有微信的环境,我们可以使用微信开发者工具,主要是可以提供一个微信的环境供我们调试各类API。
下载好工具之后需要先授权,通过微信号绑定指定的开发人员:
授权之后在微信开发者工具中选择【公众号网页】这个选项
在这个工具顶部有个URL地址栏,输入自己的页面地址:
前端代码
在前端页面中主要是通过接口获取wxConfig 的一系列参数,这里主要是url需要注意
// 获取当前页面URL(不包含#及其后面部分)
function getCurrentUrl() {
const url = window.location.href;
const hashIndex = url.indexOf('#');
if (hashIndex !== -1) {
return url.substring(0, hashIndex);
}
return url;
}
然后获取配置在前端初始化
// 获取wx.config参数
const wxConfigParams = await getWxConfig();
showStatus('获取wx.config参数成功');
console.log('配置参数:', wxConfigParams);
// 配置wx.config
wx.config({
debug: true, // 开启调试模式,便于排查问题
appId: wxConfigParams.appId, // 公众号的唯一标识
timestamp: wxConfigParams.timestamp, // 生成签名的时间戳
nonceStr: wxConfigParams.nonceStr, // 生成签名的随机串
signature: wxConfigParams.signature, // 签名
jsApiList: [
'updateAppMessageShareData',
'updateTimelineShareData',
'chooseImage',
'previewImage',
'getLocalImgData',
'getLocation',
'scanQRCode'
] // 需要使用的JS接口列表
});
成功之后就可以在ready生命周期中使用了
// 处理wx.ready事件
wx.ready(function() {
showStatus('微信JS-SDK初始化成功,可以开始使用API');
toggleLoading(false);
// 配置分享信息
const shareData = {
title: '微信JS-SDK示例',
desc: '这是一个微信JS-SDK的示例页面,展示了如何使用JS-SDK调用微信API',
link: window.location.href,
imgUrl: 'https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico',
success: function() {
showStatus('分享设置成功');
},
fail: function(res) {
showStatus('分享设置失败: ' + JSON.stringify(res), true);
}
};
// 自定义"分享给朋友"及"分享到QQ"按钮的分享内容
if (checkApiAvailable('updateAppMessageShareData')) {
wx.updateAppMessageShareData(shareData);
}
// 自定义"分享到朋友圈"及"分享到QQ空间"按钮的分享内容
if (checkApiAvailable('updateTimelineShareData')) {
wx.updateTimelineShareData(shareData);
}
});
效果
通过上面的配置之后就可以在H5页面中使用js-sdk的相关API了,比如这里点击获取位置,就可以获取用户所在的经纬度: