<?php
namespace WeChat;
class JSSDK
{
protected $appId;
protected $appSecret;
public function __construct($appid, $appsecret)
{
$this->appId = $appid;
$this->appSecret = $appsecret;
}
//获取accesstoken
public function getAccessToken()
{
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret;
$result = $this->https_request_get($url);
$result = json_decode($result, true);
return $result['access_token'];
}
//获取jsapi_ticket
private function ticket()
{
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $this->getAccessToken() . '&type=jsapi';
$result = $this->https_request_get($url);
$result = json_decode($result, true);
return $result['ticket'];
}
//生成签名用于网页
public function signature($url = null, $nonceStr = null, $timestamp = null)
{
$url = $url ? $url : $this->getUrl();
$nonceStr = $nonceStr ? $nonceStr : $this->nonceStr(16);
$timestamp = $timestamp ? $timestamp : time();
$ticket = $this->ticket();
$sign = [
'appId' => $this->appId,
'nonceStr' => $nonceStr,
'timestamp' => $timestamp,
'url' => $this->getUrl(),
'signature' => $this->getSignature($ticket, $nonceStr, $timestamp, $url),
];
return $sign;
}
//签名算法
private function getSignature($ticket, $nonceStr, $timestamp, $url)
{
return sha1("jsapi_ticket={$ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}");
}
//随机生成nonceStr
private function nonceStr($length = 16)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
//获取当前的URL
private function getUrl()
{
if (defined('PHPUNIT_RUNNING')) {
return 'http://localhost';
}
$protocol = 'http://';
if (!empty($_SERVER['HTTPS'])
|| (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
) {
$protocol = 'https://';
}
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
public function https_request_get($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
微信JSSDK生成
最新推荐文章于 2024-05-27 11:15:55 发布