微信小程序获取access_token(附源码)

获取 access_token 与获取 openid 方式一样具体如下:
在这里插入图片描述

小程序实现
  • 本地不需要传递任何参数
wx.request({
	var serverUrl = 'getAccessToken.php';
      url: serverUrl,
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log('data : ', res.data)
      },
      fail: function (res) { },
      complete: function (res) { },
    })

在这里插入图片描述

服务端实现
  • appid和秘钥自行定义,这里我随便定义的
  • 请求URL地址上篇文档已经有详细的介绍了, 一些参数不需要特别记忆知道就可以URL详解
<?php
/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */

class getAccessToken
{
    private $url;
    private $params;

    function __construct()
    {
        $this->url = 'https://api.weixin.qq.com/cgi-bin/token';//请求url
        $paramsArray = array(
            'appid' => 'wxfddfkjs54g5r5d5sdsf',//你的appid
            'secret' => 'krj9er9df883kjd4j5k435jk34fddf',//你的秘钥
            'grant_type' => 'client_credential'//微信授权类型,官方文档定义为 : client_credential
        );
        $this->params = http_build_query($paramsArray);//生成URL参数字符串

    }
	
	
    public function getTokenCurl($ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
            curl_setopt($ch, CURLOPT_URL, $this->url);
        } else {
            if ($this->params) {
                curl_setopt($ch, CURLOPT_URL, $this->url . '?' . $this->params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $this->url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}
//入口调用
$getAccessToken = new getAccessToken();
$res= $getAccessToken->getTokenCurl();
echo $res;

猜你喜欢

转载自blog.csdn.net/qq_39043923/article/details/89349554