【公众号】微信H5调用sdk分享

微信H5调用sdk分享

一、公众号配置

绑定域名

也就是只有这里的域名才能权限访问微信开发平台

引入 JS 文件

1
2
3
4
5
6
7
8
9
<script>
var wxShareScript = document.createElement("script");
wxShareScript.type = "text/javascript";
wxShareScript.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
wxShareScript.onload = function () {
// ...
};
document.head.appendChild(wxShareScript);
</script>

二、发起调用请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const params = {
href: location.href,
};
const queryString = new URLSearchParams(params).toString();
const url = `xxxx?${queryString}` // 替换为服务端接口
fetch(url)
.then((response) => response.json())
.then((data) => {
if (data.code === 0) {
const { appId, signature, nonceStr, timestamp } = data.result;
wx.config({
appId,
timestamp,
nonceStr,
signature,
jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
});
}
})
.catch((error) => {
console.error("load wxShareScript error", error);
});

三、服务端接口

去微信公众平台get appid和appsecret,同时配置IP白名单,否则接口无法调用

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// 引入 Egg.js 控制器
const { Controller } = require('egg');
// 引入 axios 库
const axios = require('axios');
const jsSHA = require('jssha');

// 微信公众号的 AppID 和 AppSecret
const appid = 'xxx';
const appsecret = 'xxx';

// 全局变量用于保存 jsapi_ticket 和过期时间
let jsapiTicket = '';
let ticketExpiresAt = 0;

/**
* 获取 access_token
* @returns {Promise<string>} access_token
*/
async function getAccessToken(ctx) {
try {
const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`);
const accessToken = response.data.access_token;
return accessToken;
} catch (error) {
ctx.logger.info('Failed to get access token:', error.response.data);
throw error;
}
}

/**
* 获取 jsapi_ticket
* @returns {Promise<string>} jsapi_ticket
*/
async function getJsApiTicket(ctx) {
try {
const accessToken = await getAccessToken(ctx);
const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`);
const ticket = response.data.ticket;
return ticket;
} catch (error) {
ctx.logger.info('Failed to get jsapi ticket:', error.response.data);
throw error;
}
}
var raw = function (args) {
var keys = Object.keys(args);
keys = keys.sort();
var newArgs = {};
keys.forEach(function (key) {
newArgs[key.toLowerCase()] = args[key];
});

var string = '';
for (var k in newArgs) {
string += '&' + k + '=' + newArgs[k];
}
string = string.substr(1);
return string;
};

class ShareController extends Controller {
/**
* 获取签名信息的接口
*/
async getWechatSignature() {
const { ctx } = this;
const url = ctx.query.href;

const timestamp = parseInt(new Date().getTime() / 1000); // 当前时间戳
const noncestr = Math.random().toString(36).substr(2, 15); // 生成随机字符串

if (!jsapiTicket || timestamp >= ticketExpiresAt) {
jsapiTicket = await getJsApiTicket(ctx);
// 设置过期时间为 7000 秒(提前200秒过期)
ticketExpiresAt = timestamp + 7000;
}

var ret = {
jsapi_ticket: jsapiTicket,
nonceStr: noncestr,
timestamp: timestamp + '',
url: url,
};

var string = raw(ret);
var shaObj = new jsSHA(string, 'TEXT');
const signature = shaObj.getHash('SHA-1', 'HEX');

// 将签名信息返回给前端
ctx.body = {
code: 0,
result: {
timestamp: timestamp,
nonceStr: noncestr,
signature: signature,
appId: appid,
},
};
}
}

module.exports = ShareController;

四、最后

有和没有的区别

最后…

如果你是个人公众号,以上你就白看了了,因为。。。

如果你是企业公众号,就可以尽情的玩耍了。。。


喜欢这篇文章?打赏一下支持一下作者吧!
【公众号】微信H5调用sdk分享
https://www.cccccl.com/20221205/公众号/微信H5调用sdk分享/
作者
Jeffrey
发布于
2022年12月5日
许可协议