微信开放的JS-SDK面向网页开发者提供了基于微信内的网页开发工具包,最直接的好处就是我们可以使用微信分享、扫一扫、卡券、支付等微信特有的能力
配置授权思路:首先要获取access_token(access_token利用缓存保存起来,方便全局访问),然后根据access_token获取jsapi_ticket,在通过获取到的jsapi_ticket以及随机生成的字符串、时间戳,再加上需要授权的页面地址url,进行SHA-1加密,返回加密字符串,最后根据加密串调用微信提供的config接口。
1.首先登录公众后后台获取appId和appsecret,然后配置JS接口安全域名,如下图,记得将那个txt文件上传到域名服务器的根目录下(index.php所在目录),否则配置不了JS安全域名
2.获取、缓存全局的access_token,以下以tp3.2框架为例,下面appid和appsecret都已配置好,请求微信提供的接口获取access_token并存入缓存
protected function getAccessToken()
{
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = S('weixin_access_token');
if (empty($data)) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$appId = C('weixin_appId');
$appSecret = C('weixin_appSecret');
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
$res = json_decode($this->httpGet($url), true);
$access_token = $res['access_token'];
S('weixin_access_token', $access_token, 7000);
} else {
$access_token = $data;
}
return $access_token;
}
2.获取微信jsapi_ticket,根据上面获取的access_token获取jsapi_ticket,并存入缓存(获取jsapi_ticket微信有100000次限制)
protected function getJsApiTicket()
{
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = S('weixin_jsapi_ticket');
if (empty($data)) {
$accessToken = $this->getAccessToken();
// 如果是企业号用以下 URL 获取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url), true);
$ticket = $res['ticket'];
S('weixin_jsapi_ticket', $ticket, 7000);
} else {
$ticket = $data;
}
return $ticket;
}
3.建立微信随机字符串
private function createNonceStr($length = 16)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
4.获取微信JS签名,注意http协议要兼容http和https,否则可能有跨域报错
//微信JS签名
protected function getSignPackage()
{
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => C('weixin_appId'),
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string,
);
return $signPackage;
}
5.在页面通过JS获取appid,noncestr,timestamp,signature这四个参数就能配置好微信分享了