php获取微信基础接口凭证Access_token

php获取微信基础接口凭证Access_token的具体代码,供大家参考,具体内容如下

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

使用AppID和AppSecret调用本接口来获取access_token。AppID和AppSecret可在微信公众平台官网-开发者中心页中获得。

1. 构造一个请求函数

php获取微信基础接口凭证Access_token
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//设置网络请求配置
public
function
_request(
$curl
,
$https
=true,
$method
=
‘GET‘
,
$data
=null){
 
// 创建一个新cURL资源
 
$ch
= curl_init();
  
 
// 设置URL和相应的选项
 
curl_setopt(
$ch
, CURLOPT_URL,
$curl
); 
//要访问的网站
 
//启用时会将头文件的信息作为数据流输出。
 
curl_setopt(
$ch
, CURLOPT_HEADER, false); 
 
//将curl_exec()获取的信息以字符串返回,而不是直接输出。
 
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, true); 
  
 
if
(
$https
){
 
//FALSE 禁止 cURL 验证对等证书(peer‘s certificate)。
 
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYPEER, false);
 
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYHOST, true);
//验证主机
 
}
 
if
(
$method
==
‘POST‘
){
 
curl_setopt(
$ch
, CURLOPT_POST, true);
//发送 POST 请求
  
//全部数据使用HTTP协议中的 "POST" 操作来发送。
 
curl_setopt(
$ch
, CURLOPT_POSTFIELDS,
$data
);
 
}
  
  
 
// 抓取URL并把它传递给浏览器
 
$content
= curl_exec(
$ch
);
  
 
//关闭cURL资源,并且释放系统资源
 
curl_close(
$ch
);
  
 
return
$content
;
}

2.获取票据并保存

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//获取令牌[access_token]
public
function
_getAccessToken(){
  
 
//指定保存文件位置
 
if
(!
is_dir
(
‘./access_token/‘
)){
 
mkdir
(iconv(
"UTF-8"
,
"GBK"
,
‘./access_token/‘
),0777,true);
 
}
 
$file
=
‘./access_token/token‘
;
 
if
(
file_exists
(
$file
)){
 
$content
=
file_get_contents
(
$file
);
 
$cont
= json_decode(
$content
);
 
if
( (time()-
filemtime
(
$file
)) <
$cont
->expires_in){
  
//当前时间-文件创建时间<token过期时间
  
return
$cont
->access_token;
 
}
 
}
  
 
$curl
=
‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=‘
.
$this
->_appid.
‘&secret=‘
.
$this
->_appsecret;
 
$content
=
$this
->_request(
$curl
);
 
file_put_contents
(
$file
,
$content
);
 
$cont
= json_decode(
$content
);
 
return
$cont
->access_token;
  
}

*出于安全考虑的话,获取到的票据可以先编码或加密再保存,使用的时候进行解码解密再使用!

以上就是本文的全部内容