PHP怎么获取微信access_token

PHPz
PHPz 原创
2020-09-04 17:24:17 1619浏览

PHP获取微信“access_token”的方法:首先保存好公众号的appid和secret;然后设置白名单;接着将一个token缓存起来;最后通过“getAccessToken”获取微信“access_token”即可。

PHP怎么获取微信access_token?

接口调用请求说明

https请求方式: GET

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数说明

参数是否必须说明
grant_type是获取access_token填写client_credential
appid是第三方用户唯一凭证
secret是第三方用户唯一凭证密钥,即appsecret

返回说明

正常情况下,微信会返回下述JSON数据包给公众号:

{"access_token":"ACCESS_TOKEN","expires_in":7200}

参数说明

参数说明
access_token获取到的凭证
expires_in凭证有效时间,单位:秒

以上是微信的公众号获取access_token文档,本章简单说下php获取token的方法和要注意的地方

1.准备的参数需要公众号的appid和secret这2个信息,同时要注意的是secret更改后你保存的也需要更改,所以不建议更改,保存好即可。

2.需要设置白名单,可以根据服务器的ip地址获取,如果实在不知道的,也没关系,因为你可以根据微信接口的报错来知道自己的ip然后设置进去。

3.access_token每天调用的次数有效,没记错的话是2K次一天,但是一个token的有效期的2小时,所以我们必须将一个token缓存起来2小时,这样才不会超过接口的调用次数。

<?php
    public function getAccessToken($appid,$secret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $res = $this->curl_get($url);
        $res = json_decode($res,1);
        if($res['errcode']!=0) throw new Exception($res['errmsg']);
        return $res['access_token'];
    }
 public function curl_get($url) {
         $headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

以上就是php获取token的代码,相对来说难度比较低。

更多相关技术知识,请访问PHP中文网

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。