標籤:ror ret 新浪 color cep src alt 操作 sign
第一步:
前往微博開放平台申請應用,地址:http://open.weibo.com/,需要企業帳號並審核通過。(微博授權審核是需要在你的web或者app上需要有微博登陸的按鈕,否者審核不會通過)
拿到App Key和App Secret之後就可以開始調取介面。
第二步:
使用者表新加欄位儲存微博返回資訊,
第三步:
去官方下載一個sdk, https://github.com/xiaosier/libweibo,直接上代碼:
/**
* 微博授權登入
*/
public function weiboLogin(){
$app_key = "3495468843"; //app key
$app_secret = "7d26eeb3fd46815a1d1ecda1cd786d29"; //app secert
$my_url = "http://".$_SERVER[‘HTTP_HOST‘]."/Home/User/weiboLogin";
//第一步:使用者同意授權,擷取code
$code = $_REQUEST["code"];//存放code
if(empty($code)){
$url = "https://api.weibo.com/oauth2/authorize?client_id=".$app_key."&response_type=code&redirect_uri=". urlencode($my_url);
echo("<script> top.location.href=‘" . $url . "‘</script>");
}
//第二步:用code換取Access Token
if(!empty($code)){
//include_once( ‘saetv2.ex.class.php‘ );
vendor("Weibo.saetv2"); //引入微博sdk
$o = new \SaeTOAuthV2( $app_key , $app_secret );
$keys = array();
$keys[‘code‘] = $code;
$keys[‘redirect_uri‘] = $my_url;
try {
$token = $o->getAccessToken( ‘code‘, $keys ) ;
}
catch (\OAuthException $e) {
}
//第三步,用Access Token擷取帳號資訊
if ($token) {
//$_SESSION[‘token‘] = $token;
//setcookie( ‘weibojs_‘.$o->client_id, http_build_query($token) );
$c = new \saetclientv2($app_key,$app_secret, $token[‘access_token‘]);
$ms =$c->home_timeline();
$uid_get = $c->get_uid();
$uid = $uid_get[‘uid‘];
$usr_info=$c->show_user_by_id($uid); //微博sdk方法擷取使用者的資訊
$m = M("Member");
$data = array();
$data[‘sex‘] = $usr_info[‘gender‘]==‘m‘?1:2;
$data[‘province‘] = $usr_info[‘province‘];
$data[‘city‘] = $usr_info[‘city‘];
$data[‘person_name‘] = $usr_info[‘name‘];
$data[‘xl_openid‘] = $usr_info[‘idstr‘];
$data[‘xl_img‘] = $usr_info[‘profile_image_url‘];
$data[‘addtime‘] = date("Y-m-d H:i:s", time());
$data[‘person_img‘] = $usr_info[‘profile_image_url‘];
$data[‘signtime‘] = date("Y-m-d H:i:s", time());
$user = M("Member")->where(array("xl_openid"=> $usr_info[‘idstr‘]))->find();
if($user){
$res = M("Member")->where(array("xl_openid"=> $usr_info[‘idstr‘]))->setField("signtime", date("Y-m-d H:i:s", time()));
if($res){
//登入成功商務邏輯
}else{
$this->error("操作異常,拒絕訪問!", U(‘user/login‘));
}
}else{
$res=$m->add($data);
if($res){
//登入成功商務邏輯
}else{
$this->error("操作異常,拒絕訪問!", U(‘user/login‘));
}
}
}else {
$this->error("授權失敗。", U(‘user/login‘));
}
}
}
php實現新浪微博授權登入