首先要将微信网页开发配置好域名
如下:
接着进入自己的测试号,联通接口
php代码如下:
public function index(){
//公众号
$appid = 'wx3aba37a42092d4ac';
$redirect_uri = urlencode('http://zhang-rui.top/vote/index.php/home/index/getcode');//将字符串以URL编码
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:". $url);//header()函数向客户端发送原始的HTTP报头
}
注意:appid是自己的测试号
用户同意授权,获取code,如下为获取code接口
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
PHP代码如下:
public function getcode(){
$code = $_GET["code"];//预定义的$_GET 变量用于收集来自method=“get”的表单中的值
// echo $code;
$json = $this->access_token($code);
//json转化成数组
$arr = json_decode($json,true);
$arr = array_change_key_case($arr,CASE_LOWER);//将数组中的键转化小写
if (isset($arr['access_token']) && isset($arr['openid'])) {
// echo "111";
$result = $this->userinfo($arr['access_token'],$arr['openid']);
print_r($result);
}else{
echo "获取access_token出错".$json;
}
}
通过code获取access_token
//获取access_token
private function access_token($code){
$appid = 'xxxxxx';//自己微信公众号的appid
$appsecret = "xxxxxx";//自己微信公众号的appsecret
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
// return $url;
$ret = https_request($url);
return $ret;
}
获取用户信息
//获取用户信息
private function userinfo($access_token,$openid){
// echo "123";
// echo $access_token;
// echo $openid;
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
$userinfo_json = https_request($url);
$userinfo_array = json_decode($userinfo_json,true);
array_change_key_case($userinfo_array,CASE_LOWER);
return $userinfo_array;
}