最近在網上看了不少關於新浪oauth2.0認證過程感受仍是有點暈乎乎的如今本身總結一下吧php
function weibo_signin_button() { $img = variable_get('weibo_button_url', 'http://www.sinaimg.cn/blog/developer/wiki/240.png'); return l(theme('image', array('path' => $img, 'alt' => t('Sign in with Weibo'))), 'weibo/redirect', array('html' => TRUE, 'query' => array('token' => 'login'))); }
首先點擊一個新浪按鈕跳轉到新浪的用戶登陸頁面,連接是http://test.com/weibo/redirect?token=signhtml
function weibo_signin_redirect() { if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], 'weibo/connect', TRUE)) { return drupal_access_denied(); } $_SESSION['ref'] = $_SERVER['HTTP_REFERER']; global $base_url; module_load_include('php', 'sinaweibo', 'saetv2.ex.class'); $key = variable_get('weibo_consumer_key', ''); $secret = variable_get('weibo_consumer_secret', ''); $o = new SaeTOAuthV2($key, $secret); $aurl = $o->getAuthorizeURL($base_url . '/weibo/callback'); drupal_goto($aurl); } 點擊http://test.com/weibo/redirect?token=sign後執行上面的方法跳轉到=$this->client_id&redirect=$url&response_type=$response_type&state=$state&display=$display這個頁面是用戶登陸頁面 若是用戶成功登陸並確認受權後會重定向
2.根據獲取的code和appkey以及appsecret獲取access token function weibo_auth_callback() { global $user; module_load_include('php', 'sinaweibo', 'saetv2.ex.class'); $key = variable_get('weibo_consumer_key', ''); $secret = variable_get('weibo_consumer_secret', ''); if ($_REQUEST['code']) { global $base_url; $o = new SaeTOAuthV2($key, $secret); $keys = array(); $keys['code'] = $_REQUEST['code']; $keys['redirect_uri'] = $base_url . '/weibo/callback'; try { $token = $o->getAccessToken( 'code', $keys ) ; } catch (OAuthException $e) { } if ($token) { $_SESSION['weibooauth_token'] = $token; $weibo_uid = $_SESSION['weibooauth_token']['uid']; } if ($user->uid == 0) { if ($uid = db_select('weibo_account') ->fields('weibo_account', array('uid')) ->condition('weibo_uid', $weibo_uid) ->execute() ->fetchField()) { // Sign in with Sina Weibo account. $user = user_load($uid); } else { // Sign up with Sina Weibo account. if(variable_get('weibo_enable_signup')) { sinaweibo_user_signup(TRUE); $post_message = variable_get('weibo_post_message'); if($post_message) { post_to_weibo($post_message); } } else { drupal_set_message(t('You have to sign up with your email address firstly.'), 'error'); } } } elseif ($user->uid > 0 && $weibo_uid > 0) { // Connect the account to Sina Weibo. $uid = db_select('weibo_account') ->fields('weibo_account', array('uid')) ->condition('weibo_uid', $weibo_uid) ->execute() ->fetchField(); if (!$uid) { sinaweibo_user_signup(FALSE); drupal_set_message(t('You have connected with Sina Weibo account.')); } else { $username = user_load($uid)->name; drupal_set_message(t('The Sina Weibo account already connected with @name. You should disconnect that account firstly.', array('@name' => $username)), 'error'); } } drupal_goto($_SESSION['ref']); } }