微信公众号获取的access_token有两种:网页授权access_token、普通access_token,前者仅用于网页端请求用户授权,获取用户信息。后者则广泛用于微信各种接口。本文需要的就是后者:普通access_token。
(另外备注一点:网页授权获取access_token是先获取到(用户同意授权之后的)code,再根据code获取access_token,而普通access_token直接通过appid、appsecret,请求一次就可获得)
php
class weixin{
private $AppID = '';//自行填写
private $AppSecret = '';//自行填写
public $tokenFile = './wxtoken.txt';//保存token的文件,有效期2小时
public $jsapiFile = './wxjsapi_ticket.txt';//保存 jsapi_ticket的文件,有限期2小时
public $getTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
public $getjsapiUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi';
public function __construct(){
$this->http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
}
public function index(){
$action = isset($_GET['do']) ? $_GET['do'] : '';
switch($action){
case 'ApiJsSignature':
$ret = $this->ApiJsSignature();//获取分享需要的签名等数据
break;
default:
echo 'default';
break;
}
}
//用于微信分享到朋友圈或给朋友的参数
public function ApiJsSignature(){
$access_token = $this->get_access_token();
$JsapiTicket = $this->get_jsapi_ticket($access_token);
$signArr = array(
'jsapi_ticket' => $JsapiTicket,
'noncestr' => $this->str_rand(16),
'timestamp' => time(),
'url' => urldecode($_POST['jsapi_url'])
);
$signStr = 'jsapi_ticket='.$signArr['jsapi_ticket'].'&nOncestr='.$signArr['noncestr'].'×tamp='.$signArr['timestamp'].'&url='.$signArr['url'];
//http_build_query()这个方法好像有问题,我使用之后返回的参数缺少字符
$signArr['signature'] = sha1($signStr);
$signArr['appid'] = $this->AppID;
echo json_encode($signArr);
}
//第二步获取jsapi_ticket
public function get_jsapi_ticket($access_token) {
if(!file_exists($this->jsapiFile)) {
$JsapiTicket = $this->resetJsapiTicket($access_token);
}else{
$fileContent=file_get_contents($this->jsapiFile);
$ticketArr = json_decode($fileContent,true);
if($ticketArr['expires_in'] <time()) {
$JsapiTicket = $this->resetJsapiTicket($access_token);
}else{
$JsapiTicket = $ticketArr['ticket'];
}
}
return $JsapiTicket;
}
public function resetJsapiTicket($access_token) {
$url = str_replace('ACCESS_TOKEN', $access_token, $this->getjsapiUrl);
$ticketJson = $this->curlPost($url);
$ticketData = json_decode($ticketJson, true);
$ticketData['expires_in'] = $ticketData['expires_in']+time();
file_put_contents($this->jsapiFile, json_encode($ticketData));
return $ticketData['ticket'];
}
//第一步获取access_token
public function get_access_token() {
if(!file_exists($this->tokenFile)) {
$access_token = $this->resetToken();//重置token并写入文件 , 返回token值
}else{
$fileContent=file_get_contents($this->tokenFile);
$tokenArr = json_decode($fileContent,true);
if($tokenArr['expires_in'] <time()) {
$access_token = $this->resetToken();
}else{
$access_token = $tokenArr['access_token'];
}
}
return $access_token;
}
//刷新、重置token, 设置获取token事件并将json数据写入文件,最后返回token值,
private function resetToken(){
$url = str_replace('APPID', $this->AppID, $this->getTokenUrl);
$url = str_replace('APPSECRET', $this->AppSecret, $url);
$tokenJson = $this->curlPost($url);
$tokenData = json_decode($tokenJson, true);
$tokenData['expires_in'] = $tokenData['expires_in']+time();
file_put_contents($this->tokenFile, json_encode($tokenData));
return $tokenData['access_token'];
}
//生成随机字符串
public function str_rand($length = 32) {
$char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if(!is_int($length) || $length <0) {
return false;
}
$string = '';
for($i = $length; $i > 0; $i--) {
$string .= $char[mt_rand(0, strlen($char) - 1)];
}
return $string;
}
//发送请求
public function curlPost($url, $data = '') {
if (! function_exists('curl_init')) {
return '';
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 可提交数组参数
$data = curl_exec($ch);
if (! $data) {
error_log(curl_error($ch));
}
curl_close($ch);
return $data;
}
}
// 调用方式: index.php?do=ApiJsSignature
$weixin = new weixin();
$weixin->index();