微信小程序获取access_token

博客简介

本篇博客介绍如何用服务器获取小程序全局唯一后台接口调用凭据(access_token)。调用绝大多数后台接口时都需使用access_token,开发者需要进行妥善保存。分为以下三个部分:

  • auth.getAccessToken接口介绍
  • 前端发送request请求
  • 后端调用getAccessToken接口

auth.getAccessToken接口介绍

  • 接口地址:GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  • 请求参数
属性 类型 默认值 必填 说明
grant_type string 填写 client_credential
appid string 小程序唯一凭证,即 AppID,可在「微信公众平台 - 设置 - 开发设置」页中获得。(需要已经成为开发者,且帐号没有异常状态)
secret string 小程序唯一凭证密钥,即 AppSecret,获取方式同 appid
  • 返回值——json数据包
属性 类型 说明
access_token string 获取到的凭证
expires_in number 凭证有效时间,单位:秒。目前是7200秒之内的值。
errcode number 错误码
errmsg string 错误信息

a.微信小程序js部分返送request请求:注意url中填写服务器代码的url

  getAccessToken:function(){
     
    var that = this;
    wx.request({
     
      url: 'https://littlede.applinzi.com/accessToken.php',
      data: {
     },
      success(res) {
     
        console.log(res.data);
        that.setData({
     
          accessToken: res.data.access_token
        })
      }
    })
  }

b.服务器部分:

  • 新建一个PHP文件
  • 将这个PHP文件的URL作为参数填入a.微信小程序js部分的url中
  • appid和秘钥secret可在微信小程序开发设置中获取(这里的仅仅是示例)
  • PHP中的代码如下:

	$appid="wxd12a86f67b482fcf1";
	//小程序秘钥
	$secret="4ae3b3c1dda4624b72f3d4e8d28097e5";
	$api="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={
       $appid}&secret={
       $secret}";
	
    //php get请求网络的方法
    function curl_get($url, &$httpCode = 0) {
     
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
	$str=curl_get($api);
	echo $str;
?>

微信小程序获取access_token_第1张图片

调用函数,输出access_token,获取成功

微信小程序获取access_token_第2张图片

你可能感兴趣的:(微信小程序开发)