微信公众号开发:获取 access_token 的两种方式 cURL 函数 和 file_get_contents 函数
关于 access_token
access_token 是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用 access_token。
access_token 的存储至少要保留 512 个字符空间。access_token 的有效期目前为 2 个小时。
接口调用说明
https 请求方式:GEThttps://api.weixin.qq.com/cgi...
参数
| 参数 | 是否必须 | 说明 |
|---|---|---|
| grant_type | Y | 获取access_token填写client_credential |
| appid | Y | 第三方用户唯一凭证 |
| secret | Y | 第三方用户唯一凭证密钥,即 appsecret |
代码块
- 方法一 :curl_init() 函数
<?php
$appid = "";
$appsecret = "";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
/*
* curl_init() 为 PHP 函数
* curl_setopt 设置 cURL 的传输选项
**/
$ch = curl_init(); // 创建一个 cURL 资源
curl_setopt($ch, CURLOPT_URL, $url); // CURLOPT_URL 目标 url 地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // CURLOPT_SSL_VERIFYPEER False: 终止 cURL 在服务器进行验证
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // CURLOPT_RETURNTRANSFER 返回原生的(Raw)输出
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
/*
* 想帅的可以利用 JSON 函数 json_decode(仅处理 UTF-8 编码数据) 来美化输出
* 当函数 assoc 参数为 true 返回的是 array, 反之是 object, 默认为 false
* */
$json_output = json_decode($output);
var_dump($json_output);- 方法二 :file_get_contents 函数
<?php $appid = ""; $appsecret = ""; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; // file_get_contents 将整个文件读入一个字符串中。 $output = file_get_contents($url); $json_output = json_decode($output, true); var_dump($json_output);
效果图
- $output
- json_decode($output)
- json_decode($output, true)
相关推荐
曾是土木人 2020-10-31
yegen00 2020-10-21
soralaro 2020-10-11
katanaFlower 2020-09-18
wytzsjzly 2020-08-17
88407710 2020-08-17
ChinaJoeEE 2020-08-16
CyborgLin 2020-08-15
Blueberry 2020-08-15
PinkBean 2020-08-11
katanaFlower 2020-08-03
hunningtu 2020-07-30
阿债的方寸天地 2020-06-28
pingyan 2020-06-25
wytzsjzly 2020-06-25
阳光岛主 2020-06-25
阿债的方寸天地 2020-06-16