文档参考:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
3个文件
(假设)服务器域名:http://www.mytest.com/
index.php、oauth2.php、test.php
1、用户同意授权,获取code
index.php内容
connect_redirect=1 是腾讯(微信)服务器配置的动态参数, 意为只触发一次请求, 超时也不重发。
<?php
$appid = '你的APPID';
header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'
&redirect_uri=http://www.mytest.com/oauth2.php
&response_type=code
&scope=snsapi_userinfo
&state=state
&connect_redirect=1
#wechat_redirect');
?>
2、oauth2.php内容
<?php
error_reporting(0);
session_start();
$appid = '你的APPID';
$appsecret = '你的APPSECRET ';
$code = $_GET['code'];//获取微信服务器转发过来的code
//code换取网页授权access_token
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>错误1:</h1>'.$token->errcode;
echo '<br/><h2>错误信息1:</h2>'.$token->errmsg;
exit;
}
//刷新access_token
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误2:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息2:</h2>'.$access_token->errmsg;
exit;
}
//拉取用户信息
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//$user_info用户信息对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误4:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息4:</h2>'.$user_info->errmsg;
exit;
}
//用户信息存到session 全局可调用
$_SESSION['openid'] = $user_info->{'openid'};
$_SESSION['nickname'] = $user_info->{'nickname'};
$_SESSION['head'] = $user_info->{'headimgurl'};
//最后跳转到测试页面 test.php
header('location:http://www.mytest.com/test.php');
?>
3、test.php 内容
<?php
session_start();
var_dump($_SESSION);
//接下来想怎么玩儿就看你自己咯。
?>
网友评论