/**
* 获取微信用户信息
*/
public function index()
{
if(empty($this->data["code"])) $this->result('', -1, 'code不能为空!');
$appid = config('appid');//微信的appid
$secret = config('secret');//微信的appsecret
$code = $this->data["code"];//前端获取到的code
$token = $this->generate_rand_str('12');//12位随机数
//第一步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = $this->getJson($oauth2Url);
//第二步:根据全局access_token和openid查询用户信息
$access_token = $oauth2["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = $this->getJson($get_user_info_url);
$this->result($userinfo, 1, '微信用户信息');
}
/**
* 生成随机字符串
*/
function generate_rand_str($length = 8, $type = 0) {
$a = 'abcdefghijklmnopqrstuvwxyz';
$A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$n = '0123456789';
switch ($type) {
case 1: $chars = $a; break;
case 2: $chars = $A; break;
case 3: $chars = $n; break;
case 4: $chars = $a.$A; break;
case 5: $chars = $a.$A.$n; break;
default: $chars = $a.$n;
}
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $str;
}
/**
* 发起请求
*/
function getJson($url){
$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($ch);
return json_decode($output, true);
}
tp5 接入微信登陆
最新推荐文章于 2024-05-23 01:00:00 发布