Files
spacestation/common/libraries/Jssdk.php
T
2025-07-27 12:22:34 +08:00

77 lines
2.1 KiB
PHP

<?php
class Jssdk
{
private $appId;
private $appSecret;
private $redis;
public function __construct($group = 'default')
{
$CI = &get_instance();
if (is_array($group)) {
$this->appId = $group['appid'];
$this->appSecret = $group['appSecret'];
} else {
$CI->load->config('wechat');
$config = $CI->config->item($group);
$this->appId = $config['appid'];
$this->appSecret = $config['appSecret'];
}
$r = &load_cache('redis');
$this->redis = $r->redis();
$param = array('appid' => $this->appId, "secret" => $this->appSecret);
$CI->load->library("hd_wechat", $param);
$this->hd_wechat = $CI->hd_wechat;
$this->hd_wechat->init($param);
}
public function getSignPackage($url = '')
{
$jsapiTicket = $this->getJsApiTicket();
if (!$url) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if ($_SERVER['QUERY_STRING']) {
//$url .= '?'.$_SERVER['QUERY_STRING'];
}
}
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => $this->appId,
"timestamp" => $timestamp,
"nonceStr" => $nonceStr,
"signature" => $signature,
"url" => $url,
"rawString" => $string,
'jsapi_ticket' => $jsapiTicket
);
return $signPackage;
}
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;
}
private function getJsApiTicket()
{
$ticket = $this->hd_wechat->api_ticket();
return $ticket;
}
}