一、登陸微信公衆平臺,在 "開發者中心" 找到
php
點擊右側的修改。html
受權回調域名配置規範爲全域名而且不帶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鑑權。json
如:www.test.comapi
二、獲取code微信
請求受權頁面構造:app
$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'; curl
header("Location:".$url); url
}spa
三、在域名根目錄下,新建一個文件,命名爲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