前端
$('#weibologin').click(function(){
location.href = 'https://api.weibo.com/oauth2/authorize?client_id=1228667031&response_type=code&redirect_uri=http://new3.xuanwumobile.com/html/login_win.html';
});
var Request = new UrlSearch(); //实例化
if(Request.code){
$.ajax({
url:'http://cloud.xuanwumobile.com/api/Timer/aaaaaa',
data:'code='+Request.code,
type:'post',
cache:false,
dataType:'json',
success:function(ret) {
if(ret.error){
tanKuang('授权出错!');
return;
}else{
var wbtoken = ret.uid;
alert(wbtoken)
}
},
error : function(err) {
alert(err);
}
});
}
function UrlSearch() {
var name, value;
var str = location.href; //取得整个地址栏
var num = str.indexOf("?")
str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
var arr = str.split("&"); //各个参数放到数组里
for (var i = 0; i < arr.length; i++) {
num = arr[i].indexOf("=");
if (num > 0) {
name = arr[i].substring(0, num);
value = arr[i].substr(num + 1);
this[name] = value;
}
}
}
后端
header("Access-Control-Allow-Origin: *");
$code = $_REQUEST['code'];
$body_json = array( //不能用,得把参数放到url里,方法是post,但form-data是空,否则报错:miss client id or secret
'client_id' => '1228667031',
'client_secret' => '2363c310edc1c847fa80a4feedcb211b',
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => 'http://new3.xuanwumobile.com/html/login_win.html'
);
$body = json_encode($body_json);
$header = array(
'Accept:application/json',
'Content-Type:application/json;charset=utf-8',
);
//$url = 'https://api.weibo.com/oauth2/access_token';
$url = 'https://api.weibo.com/oauth2/access_token?client_id=1228667031&client_secret=XXXXXXXXXXXX&grant_type=authorization_code&redirect_uri=http://new3.xuanwumobile.com/html/login_win.html&code=' . $code;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, false);//formdata为false(即以前的$body_json )
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result, true);
return json($res);