微信分享 JSSDK 实现

最近公司要做个微信分享功能,记录下来以便后来复制粘贴,哈哈哈。
原谅我,我在做这个之前从网上的确复制粘贴了,最后发现都没法用,哈哈,只能自己看接口文档了。在这之前,首先你要获取 appid 和 appSecret,然后还要配置 JS 安全域名,还有就是 IP 白名单,这些我就不说了,有了微信公众号后台轻松搞定

后端

我使用的是世界上最好的语言,不说大家都知道是什么了吧!哈哈哈,我就直接上代码了,注意点在代码里面看。注意项目用的 thinkphp 框架,所以 Cache 根据实际使用,不能一股脑的粘贴啊

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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

use Think\Cache;

class WeChat
{
// 你的 appid
private $appId = '';
// 秘钥
private $appSecret = '';
// 获取 token 的 url
private $getAccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token';
// 获取 jsticket 的 url
private $getJsTicketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';

private $cacheLiefTime = 3600;

private $cacheKey = 'ticket';

/**
* 获取签名
*
* @time at 2018年12月10日
* @param $url
* @return array
*/
public function getSignature($url)
{
$nonceStr = $this->createNonceStr(18);
$timeStamp = time();
$params = [
'jsapi_ticket' => $this->getJsTicket(),
'noncestr' => $nonceStr,
'timestamp' => $timeStamp,
];
// 只有唯一的注意点,就是不要把 url 放在 http_build_query 函数里面,它会转义
// 验证你的签名请到这里 http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
$signature = sha1(http_build_query($params) . '&url=' . $url);

return ['noncestr' => $nonceStr, 'timestamp' => $timeStamp, 'signature' => $signature, 'appid' => $this->appId];
}

/**
* 获取 TOKEN
*
* @time at 2018年12月10日
* @return void
*/
private function getAccessToken()
{
$params = [
'grant_type' => 'client_credential',
'appid' => $this->appId,
'secret' => $this->appSecret,
];

$res = $this->httpGet($this->getAccessTokenUrl .'?'.http_build_query($params));
$res = json_decode($res, true);
if (isset($res['errcode'])) {
return false;
}

return $res['access_token'];

}

/**
* 获取签名
*
* @time at 2018年12月10日
* @return void
*/
private function getJsTicket()
{
$ticket = cache($this->cacheKey);

if ($ticket) {
return $ticket;
}

$accessToken = $this->getAccessToken();

$params = [
'access_token' => $accessToken,
'type' => 'jsapi',
];

if (!$accessToken) {
return false;
}
$res = $this->httpGet($this->getJsTicketUrl .'?'.http_build_query($params));
$res = json_decode($res, true);

if (isset($res['errcode']) && $res['errcode']) {
return false;
}
Cache::remember($this->cacheKey, $res['ticket'], $this->cacheLiefTime);

return $res['ticket'];
}

private function httpGet($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);

return $res;
}

private function createNonceStr($n)
{
if (!is_numeric($n)) {
return false;
}
$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$nonceStr = '';
$strLen = strlen($str);
for ($i = 1; $i < intval($n); $i++) {
$nonceStr .= $str[rand(0, $strLen-1)];
}
return $nonceStr;
}
}

前台

引入 http://res2.wx.qq.com/open/js/jweixin-1.4.0.js 网上都是 1.2.0,抄的我好累

前端代码
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
// 注意微信文档提到 url 不允许带 # 后面的内容,所以就分割吧, 还有下面你看一下就懂了吧。
// 微信好多接口都换了,使用也和网上的一点也不一样了,所以如果当你看到这篇文章文章使用不能成功的时候,建议你去看微信文档, 不要再抄这个了。还有就是调试期间把 debug 开下来。
var url = window.location.href.split('#')[0];
$.post("{:url('Index/getWxConfig')}", {"url": url}, function (response){
var params = {}
params.debug = false;
params.appId = response.data.appid;
params.timestamp = response.data.timestamp;
params.nonceStr = response.data.noncestr;
params.signature = response.data.signature;
params.jsApiList = ['updateAppMessageShareData','updateTimelineShareData'];
wx.config(params);
wx.ready(function () {
wx.updateAppMessageShareData({
title: '我就是不信',
desc: '微信分享成功了没',
link: url,
imgUrl: 'http://aaaa.gaiwenkeji.com/data/upload/qrcode/7.png?id=1544524256',
type: 'link',
dataUrl: '',
});
wx.updateTimelineShareData({
title: '我相信了, 能不信吗',
link: url,
imgUrl: 'http://aaaa.gaiwenkeji.com/data/upload/qrcode/7.png?id=1544524256',
})
})

以上便是微信分享的所有东西,没有什么坑。坑就是我抄网上的。还有就是签名 URL 转义的,其他就没咯。

补充

2018/12/24 新的微信接口在安卓系统会无效,建议使用老接口,IOS 上可以继续使用新的接口