————————————————–获取 token———————————————-
/**
* 获得access_token
* @return bool
*/
function getAccessToken(){
$appid = C("APPID");
$secret = C("APPSECRET");
$token_file = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/Public/access_token";
//读取文件内容
$content = json_decode(file_get_contents($token_file));
//获得access_token的凭证有效时间
$expires_in = $content->expires_in;
if(time()-filemtime($token_file) < $expires_in){
//保存的token有效,返回token值
return $content->access_token;
}else{
//保存的token无效,重新修改文件的数据
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$str = file_get_contents($url);
$json = json_decode($str);
$token = $json->access_token;
if($token){
file_put_contents($token_file,$str);
return $token;
}return false;
}
}
———————————————静默授权 获取OpenID———————————————
/**
* 通过授权获得用户唯一标识openid
* @param string $parameter
* @return mixed|null|void
*/
protected function getOpenid($parameter = ''){
if(session("openid")){
return session("openid");
}else{
$appID = C('APPID');
$appsecret = C('APPSECRET');
//1,用户同意授权,获取code
if (!isset($_GET['code'])){
//触发微信返回code码
$url = C("HOST").__ACTION__.$parameter;
$url = urlencode($url);
$authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appID&redirect_uri=$url&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
Header("Location: $authUrl");
}else{
//获取code码,以获取openid
$code = $_GET['code'];
}
//2,获得网页授权access_token
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appID&secret=$appsecret&code=$code&grant_type=authorization_code";
$data = file_get_contents($url);
$data = json_decode($data);
//获取用户openid;
$openid = $data->openid;
//存储openid
session('openid', $openid);
return $openid;
}
}