微信开发之SDK

class JSSDK {
private $appId;//appid
private $appSecret;//应用密钥
// echo $appId;
// echo $appSecret;
public function __construct($appId, $appSecret) {
$this->appId = $appId;
$this->appSecret = $appSecret;
}

public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
$url = "http://$_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"     => $this->appId,
  "nonceStr"  => $nonceStr,
  "timestamp" => $timestamp,
  "url"       => $url,
  "signature" => $signature,
  "rawString" => $string
);
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;
}

public function getJsApiTicket() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
return $ticket;
}

public function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
return $access_token;
}
function httpGet($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$temp = curl_exec($ch);
curl_close($ch);
return $temp;

}

}
?>


$jssdk = new JSSDK("you APPID", "you appSecret");
$signPackage = $jssdk->getSignPackage();
?>

有不足之处还望提出。

你可能感兴趣的:(微信开发之SDK)