微信公众平台,通过网页授权可获取用户的基本信息,具体的借口其实公众平台的接口已经讲的很清楚了,但是感觉没有具体的代码 有时候看起来还是很别扭,为了以后方便看,我把自己测试的代码贴一下,实际项目中 可根据个人需求自己去改。
大致步骤:
1、通过test.php获取code,并跳转至test2.php
2、通过appid、secret、code获取openid,access_token值
3、通过openid和access_token获取到用户基本信息
测试代码:
test.php:
<?php
$str="http://www.xxx.com/test2.php";
$str_url=urlencode($str);
$appid = "wxxxxxxxxxxxxxxxx0";//appid 在公众号中获得
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$str_url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
header("Location:".$url);
?>
test2.php:
<?php
$appid = "wxxxxxxxxxxxxxxxx0";//公众平台中获得
$secret = "xxxxxxxxxxx";//公众平台中获得
$code = $_GET["code"];//上一步跳转过来获取到code值
var_dump($code);
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
//通过appid、secret、code获取openid,access_token值
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $get_token_url);
$res = curl_exec($curl);
curl_close($curl);
var_dump($res);
$json_obj = json_decode($res,true);
//通过openid和access_token获取用户基本信息
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $get_user_info_url);
$res = curl_exec($curl);
curl_close($curl);
var_dump($res);
//解析json
$user_obj = json_decode($res,true);
var_dump($user_obj);
?>