1、登录微信公众平台,在 "开发者中心" 找到
点击右侧的修改。
授权回调域名配置规范为全域名并且不带http,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权。
如:www.test.com
2、获取code
请求授权页面构造:
$appid = "公众号在微信的appid";
$url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘.$appid.‘&redirect_uri=http://www.test.com/oauth.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect‘;
header("Location:".$url);
}
3、在域名根目录下,新建一个文件,命名为oauth.php(授权回调地址),
<?php
$appid = "公众号在微信的appid";
$secret = "公众号在微信的app secret";
$code = $_GET["code"];
$url = ‘https://api.weixin.qq.com/sns/oauth2/access_token‘; //请求地址
//$ref_url = http://www.baidu.com; //来源页面
$data = array( //提交的数据
"appid" => $appid,
"secret" => $secret,
"code" => $code,
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//curl_setopt($ch, CURLOPT_REFERER, $ref_url);
curl_setopt($ch, CURLOPT_POST, TRUE); //以POST方式提交
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //超时时间
$contents = curl_exec($ch); //执行并获取返回数据
curl_close($ch);
$json_obj = json_decode($contents,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‘;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
//解析json
$user_obj = json_decode($res,true);
$_SESSION[‘user‘] = $user_obj;
print_r($user_obj);
?>
ps:参考
http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html
http://huangqiqing123.iteye.com/blog/2005770