首页 > php微信开发的时候 如何把access_token长期有效的保存,求高手解答

php微信开发的时候 如何把access_token长期有效的保存,求高手解答

<?php 
 $appid="wx44a58ea3509d09fa";
 $appsecret="d4624c36b6795d1d99dcf0547af5443d";
 $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
 //1、初始化CURL回话
 $ch=curl_init();
 //2、设置CURL选项
 curl_setopt($ch, CURLOPT_URL, $url);
 //将请求的结果以文件流的形式返回
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 //执行一个curl
 $outopt=curl_exec($ch);
 //4、关闭curl回话
 curl_close($ch);
$access_token_arr=json_decode($outopt,true);
$access_token= $access_token_arr['access_token'];
 echo $access_token;
 ?>

计划任务,定时刷新


你需要https://github.com/dodgepudding/wechat-php-sdk


access_token 你可以长期保存但是只有7200秒的有效期.

保存方式:

  1. 文件

  2. 数据库

  3. redis


我来说个土方法,数据库建一个表,字段有id,content,updated_at
初始化放一条数据进去:1,accesstoken,1440121354
然后需要获取access_token的时候,用现在的时间戳time()去数据库里查where id=1 and updated_at> time()-失效时间
要是获取过来有值,那就直接拿来用,要是没有说明时间太久了,重新获取下accesstoken,然后存到数据库里,更新时间戳


抖个机灵,用Redis,设置一个过期时间
之后做微信相关开发时打算这么干


https://github.com/thenbsp/wechat/blob/master/src/AccessToken.php

【热门文章】
【热门文章】