微信接口常用接口练习

1.获取access_token

官方文档:https://mp.weixin.qq.com/wiki/14/9f9c82c1af308e3b14ba9b973f99a8ba.html

access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

可以使用AppID和AppSecret调用本接口来获取access_token。没有公众号可以申请公众测试号,微信所有接口都是HTTPS协议

 

接口调用请求说明

http请求方式: 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 凭证有效时间,单位:秒


错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):

{"errcode":40013,"errmsg":"invalid appid"}

接下来是我的代码测试:
wx79cdc003ba226051
de7b345d5dd3ed16d8deda7d5a325892
在浏览器上输入:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx79cdc003ba226051&secret=de7b345d5dd3ed16d8deda7d5a325892
可以得到返回的json字符串
{"access_token":"9f0re0AVKVHX-qIbCKC1rwFwTKITlR7IOmrudXtDhVEL1V7xi1pDtFxJnNzZ4qCAoY9fFXGL-UWNUfjYLSkZ4GW5nTnW4c8hYmi5i9zCrUcYISjAHACMW","expires_in":7200}
至此 access_token获取完毕
 使用CURL扩展
<?php

$appid = "wx79cdc003ba226051";
$appsecret = "de7b345d5dd3ed16d8deda7d5a325892";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($ch);
curl_close();
$info = json_decode($output,true);//将json字符串转换为数据
var_dump($info);
$access_token = $info['access_token'];
var_dump($access_token);

参考博客:http://blog.csdn.net/yanhui_wei/article/details/21530811

 

posted @ 2017-04-28 14:03  周起  阅读(794)  评论(0编辑  收藏  举报