fastadmin微信小程序获取access_token

本文旨在利用fastadmin中微信管理插件获取微信小程序access_token

1.微信管理插件中配置:app_id和appsecret

//获取微信配置
$config    = get_addon_config('wechat');
$appId     =  $config['app_id'];
$appSecret =  $config['appsecret'];

2. 设置access_token保存路径

//access_token文件保存路径

$token_file = ROOT_PATH . 'public' .DS. 'access_token';

3. 考虑过期问题,将获取的access_token存储到某个文件中, 不用重复请求

$life_time = 7200;

if (file_exists($token_file) && time()-filemtime($token_file)<$life_time) {
        // 存在有效的access_token
        return file_get_contents($token_file);
}

4. 发送请求,目标url可以小程序api文档中查找

// 目标URL:
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;

//向该URL,发送GET请求
 
$result =Http::sendRequest($url);

Http::sendRequest 是使用fastadmin中的http工具, 可以修改为自己的curl请求工具

5.返回access_token

if (!$result['ret']) {
     return false;
}

 // 存在返回响应结果

 $result_obj = json_decode($result['msg']);

 // 写入

file_put_contents($token_file, $result_obj->access_token);

return $result_obj->access_token;

以上是保存access_token在本地, 可以在7200秒内,不用重复请求, 代码示例供参考, 供大佬们指教

完整代码:

 /**
     * @return 小程序获取 access_token
     * 
     */
    public function get_access_token() {
        //access_token文件保存路径
        $token_file = ROOT_PATH . 'public' .DS. 'access_token';

        #获取系统配置
        $config = get_addon_config('wechat');
        $appId =  $config['app_id'];
        $appSecret =  $config['appsecret'];
        // 考虑过期问题,将获取的access_token存储到某个文件中
        $life_time = 7200;
        if (file_exists($token_file) && time()-filemtime($token_file)<$life_time) {
            // 存在有效的access_token
            return file_get_contents($token_file);
        }
        // 目标URL:
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
        //向该URL,发送GET请求
        $result =Http::sendRequest($url);

        if (!$result['ret']) {
            return false;
        }
        // 存在返回响应结果
        $result_obj = json_decode($result['msg']);
        // 写入
         file_put_contents($token_file, $result_obj->access_token);
        return $result_obj->access_token;
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值