- 获取到token
首先把公众号的 appid 和 appsecret 拿到
然后调用这两个获取到网址,再访问该网址获取到token值
使用
file_get_contents($url)
访问该网址,然后用json_decode() 解析还有另一种方法就是使用
curl
去访问该网址后面就是要使用到这个access_token 去做其他几口了
下面就是一个获取用户列表以及通过用户列表去获取用户的基本信息
<?php
$appid = "wxe65fd69d2da5b545";
$appsecret = "4be05eba35d47feb16184dc101361ea0";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret."";
$output = (array)json_decode(gettoken($url));
//$output['access_token']
/***
* 获取到用户列表
***/
$user_list_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$output['access_token'];
// echo $user_list_url;
$user_result = (array)json_decode(gettoken($user_list_url));
$useropenidarr = (array)$user_result['data'];
//第一个用户的 openid $useropenidarr['openid'][0]
// 获取单用户的基本信息
// $user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$output['access_token']."&openid=".$useropenidarr['openid'][0]."&lang=zh_CN";
// $user_info_result = json_decode(gettoken($user_info_url));
// echo '<pre>';
// print_r($user_info_result);
// echo '</pre>';
//循环获取用户的openid
foreach ($useropenidarr['openid'] as $openid)
{
$user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$output['access_token']."&openid=".$openid."&lang=zh_CN";
$user_info_result = json_decode(gettoken($user_info_url));
echo '<pre>';
print_r($user_info_result);
echo '</pre>';
}
function gettoken($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回的结果作为变量存储,不直接输出
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36");
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function longtoshort($data,$url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36");
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回的结果作为变量存储,不直接输出
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>