微信公众平台开发---获取accessToken

来源:互联网 发布:淘宝店美工多少钱 编辑:程序博客网 时间:2024/05/21 00:55

微信公众平台开发—获取accessToken

一、accessToken简介

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

二、临时获取

1、在线测试

https://mp.weixin.qq.com/debug/
这里写图片描述
需要填的是appid和secret
返回结果
这里写图片描述

2、浏览器

将上面获取结果的请求地址填到浏览器上,也可以获取access_tokenhttps请求方式: GET

https://api.weixin.qq.com/cgi-bin/token?
grant_type=client_credential&appid=APPID&secret=APPSECRET
这里写图片描述

三、运用php代码获取

Curl 运用查看文档
这里写图片描述

Curl01.php$ch = curl_init(); //初始化//设置//设置访问的urlcurl_setopt($ch,CURLOPT_URL,"http://www.baidu.com");//只获取页面内容,但不输出curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//设置不需要的头信息curl_setopt($ch,CURLOPT_HEADER,false);//执行//返回结果一字符串形式接收$str = curl_exec($ch);//关闭curl_close($ch);//将结果输出echo $str;//可以将他封装为方法//如curl.php

结果:

这里写图片描述

Curl.php//获取accesstokenfunction _request($curl,$https=true,$method="get",$data=null){//    初始化会话    $ch = curl_init(); //初始化//    设置curl会话    curl_setopt($ch,CURLOPT_URL,$curl); //设置访问的url    curl_setopt($ch,CURLOPT_HEADER,false);//设置不需要的头信息    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//只获取页面内容,但不输出    if ($https == true){//        不做服务器端的认证        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//        不做客户端的认证、、        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);    }    if ($method == "post"){//        设置请求是post方式        curl_setopt($ch,CURLOPT_POST,true);//        设置post请求数据        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);    }//    执行curl会话    $str = curl_exec($ch);//    关闭会话    curl_close($ch);    return $str;}//调用这个函数//echo _request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx223bdbe885213d19&secret=01feca4312396c90578f87e78536d841");//获取accesstoken 修改两个小时有效期的问题function _getAccesstoken(){//    将获取到的token存到文件中,在有效期内从文件中获取    $file = "./accesstoken";//    判断这个文件是否存在    if (file_exists($file)){        $content = file_get_contents($file);        $content = json_decode($content);//        判断是否在有效期内        if (time()-filemtime($file)<$content->expires_in){            return $content->access_token;        }    }    $content = _request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx223bdbe885213d19&secret=01feca4312396c90578f87e78536d841");    file_put_contents($file,$content);    $content = json_decode($content);    return $content->access_token;}
echo _getAccesstoken();

结果:这里写图片描述

原创粉丝点击