[精讚] [會員登入]
294

使用Yahoo OAuth2 2/2

使用Yahoo OAuth2認證我的網頁

此文完整連結 http://n.sfs.tw/10725

複製連結 使用Yahoo OAuth2 2/2 @新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2017-02-05 01:58:40 最後編修
2017-02-05 01:57:00 By 瘦河馬
 

此文分為兩個單元
使用Yahoo OAuth2 1/2
使用Yahoo OAuth2 2/2

前文已申請完yahoo的api後,接下來實作的部分,原先我參考了Jex’s note 不寫下來絕對會忘…的內容,原先我也如他的原先以為只要照著做,就能順利的運作,所以我就照著他的範例來做,但是怎麼試都會出現ERROR:

$session = YahooSession::requireSession(OAUTH::CONSUMER_KEY, OAUTH::CONSUMER_SECRET, OAUTH::APP_ID);

這裡面的YahooSession到底是什麼東西啊,為什麼突然出現?後來發現它引入https://github.com/yahoo/yos-social-php/blob/master/lib/OAuth.php這個library,它的年代已經過去,同時它的方法是用YQL的方式取回資料,所以我就和Jex說的一樣:我只好參考網路的資源重刻了一個輪子:

使用OAuth2的方法來作認證

雖然Jex無法解決我的問題,但摸索中也了解了oauth2的運作,這比直接得到一個輪子有意思。以下和Jex一樣,使用CI3作為範例:

四、建立一個library

這個library 來自於[3] 由saurabhsahni寫的library,/application/libraries/Yahoooauth2.php

<?php
/*
Example class to access Yahoo OAuth2 protected APIs, based on https://developer.yahoo.com/oauth2/guide/
Find documentation and support on Yahoo Developer Network: https://developer.yahoo.com/forums
*/
class YahooOAuth2 {
  const AUTHORIZATION_ENDPOINT  = 'https://api.login.yahoo.com/oauth2/request_auth';
  const TOKEN_ENDPOINT   = 'https://api.login.yahoo.com/oauth2/get_token';
  public function fetch($url,$postdata="",$auth="",$headers="") {
        $curl = curl_init($url);
        if($postdata) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postdata));
        }
        else {
            curl_setopt($curl, CURLOPT_POST, false);
        }
        if($auth){
            curl_setopt($curl, CURLOPT_USERPWD, $auth);
        }
        if($headers){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec( $curl );
        if (empty($response)) {
            // some kind of an error happened
            die(curl_error($curl));
            curl_close($curl); // close cURL handler
        } else {
            $info = curl_getinfo($curl);
            curl_close($curl); // close cURL handler
            if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
                echo "Received error: " . $info['http_code']. "\n";
                echo "Raw response:".$response."\n";
                die();
            }
        }
        return $response;
  }
  public function getAuthorizationURL($client_id,$redirect_uri,$language="en-us") {
        $url = self::AUTHORIZATION_ENDPOINT;
        $authorization_url=$url.'?'.'client_id='.$client_id.'&redirect_uri='.$redirect_uri.
        '&language='.$language.'&response_type=code';
        return $authorization_url;
  }
  public function get_access_token($clientId, $clientSecret,$redirect_uri,$code) {
        $url=self::TOKEN_ENDPOINT;
        $postdata=array("redirect_uri"=>$redirect_uri,"code"=>$code,"grant_type"=>"authorization_code");
        $auth=$clientId . ":" . $clientSecret;
        $response=self::fetch($url,$postdata,$auth);
        // Convert the result from JSON format to a PHP array
        $jsonResponse = json_decode( $response );
        return $jsonResponse->access_token;
  }
}
?>

五、controller的部分,放在你的 controller function中

        $this->load->library('Yahoooauth2');
        define("CONSUMER_KEY", $this->config->item("yahoo_consumer_key"));
        define("CONSUMER_SECRET",$this->config->item("yahoo_consumer_secret"));
        $redirect_uri="http://".$_SERVER['SERVER_NAME'] . "/auth/login?step=8";  //設定你的回呼路徑
        $social_endpoint = "https://social.yahooapis.com/v1/user/me/profile?format=json";
        if (isset($_GET['code'])){
          $code=$_GET['code'];
        }
        else {
          $code=0;
        }
        if($code){
          try{
            #oAuth 3-legged authorization is successful, fetch access token
            $token=$this->yahoooauth2->get_access_token(CONSUMER_KEY,CONSUMER_SECRET,$redirect_uri,$code);
            #access token is available. Do API calls.
            $headers= array(
                'Authorization: Bearer '.$token,
                'Accept: application/json',
                'Content-Type: application/json'
            );
            //Fetch Advertiser Name and Advertiser ID
            $resp=$this->yahoooauth2->fetch($social_endpoint,$postdata="",$auth="",$headers);
            $jsonResponse = json_decode( $resp);
            $email = $jsonResponse->profile->emails[0]->handle;
            $name = $jsonResponse->profile->familyName .  $jsonResponse->profile->givenName;
            $gender =  ($jsonResponse->profile->gender=="M")? 1:0;
            $thumb = $jsonResponse->profile->image->imageUrl;
            $guid =  $jsonResponse->profile->guid;
         }catch(Exception $e){
              $msg= "Yahoo認證失敗:".$e->getMessage();
         }finally{
            print $msg;
         }
        }
        else {
        /* no valid access token available, go to authorization server */
          header("HTTP/1.1 302 Found");
          header("Location: " . $this->yahoooauth2->getAuthorizationURL(CONSUMER_KEY,$redirect_uri));
          exit;
        }

簡略說明:
2,3 行我把key/secret的值放在config中
4 設定你的回呼路徑
6-11,36-41 如果yahoo沒有回傳code,則導到yahoo進行授權確認
24 取得回呼的資料,是一個物件
25-29 回呼內容,可參考下面的物件內容:

六、取得的物件資料

stdClass Object

(

    [profile] => stdClass Object

        (

            [guid] => FRxxxxxxxxxxxxUU4

            [addresses] => Array

                (

                    [0] => stdClass Object

                        (

                            [city] =>

                            [country] => TW

                            [current] => 1

                            [id] => 1

                            [postalCode] =>

                            [state] =>

                            [street] =>

                            [type] => HOME

                        )

 

                    [1] => stdClass Object

                        (

                            [city] =>

                            [country] => TW

                            [current] => 1

                            [id] => 2

                            [postalCode] =>

                            [state] =>

                            [street] =>

                            [type] => WORK

                        )

 

                )

 

            [ageCategory] => A

            [created] => 2016-04-03T19:07:37Z

            [emails] => Array

                (

                    [0] => stdClass Object

                        (

                            [handle] => yourname@yahoo.com.tw

                            [id] => 1

                            [primary] => 1

                            [type] => HOME

                        )

 

                )

 

            [familyName] => 張

            [gender] => M

            [givenName] => .00

            [image] => stdClass Object

                (

                    [height] => 192

                    [imageUrl] => https://s.yimg.com/dh/ap/social/profile/profile_b192.png

                    [size] => 192x192

                    [width] => 192

                )

 

            [intl] => tw

            [jurisdiction] => tw

            [lang] => zh-Hant-TW

            [memberSince] => 2016-04-02T23:14:00Z

            [migrationSource] => 1

            [nickname] => .河馬

            [notStored] => 1

            [nux] => 0

            [phones] => Array

                (

                    [0] => stdClass Object

                        (

                            [id] => 10

                            [number] => 886-9xxxxxx1

                            [type] => MOBILE

                        )

 

                )

 

            [profileMode] => PUBLIC

            [profileStatus] => ACTIVE

            [profileUrl] => http://profile.yahoo.com/FRxxxxxxxxxU4

            [timeZone] => Asia/Shanghai

            [isConnected] => 1

            [profileHidden] =>

            [bdRestricted] => 1

            [profilePermission] => PRIVATE

            [uri] => https://social.yahooapis.com/v1/user/FRxxxxxxxxxxU4/profile

        )

)

 

能夠取得這麼完整的資料,相信你一定會很高興,祝你們使用愉快

參考資料

[3] https://github.com/saurabhsahni/php-yahoo-oauth2


原文 2016-04-05 00:04:26

你可能感興趣的文章

PHP程式經驗 #1 -- 靜態的物件比動態物件快 驗證 1. 使用動態物件函式 > 使用靜態物件函式。 2. 使用有宣告的靜態物件函式 > 使用動態無宣告的靜

[PHP] 台灣身分證號及檢查程式 台灣身分證號及PHP檢查程式

利用 php 木馬作為駭客攻擊的手法 利用 php 木馬作為駭客攻擊的手法

[PHP] 2個程式的觀念 整理2個PHP的程式觀念,參考參考。

[CI3] 使用和修改日曆類別 calendar library CI3有一個日曆圖書館 library,可以快速的建立一個日曆,但是想修改讓他更棒

[PHP] IPv6檢查IP是否在某個網段內 mtachcidr6 要檢查IPv6是否在某個IPv6的網段內?

[PHP] CodeIgniter 3+pure+smarty安裝及環境設置2/2 PHP framework CodeIgniter 3+ pure CSS +smarty Template Engine的整合#2

[PHP] 位元運算 (Bitwise operation)及和PERL比較 PHP 的位元運算,及和PERL比較整理

[PHP7] 利用Memcached 儲存 Session Memcached+ PHP7,利用Memcached 儲存 Session。

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔

我有話要說


限制:留言最高字數1000字,超過部分會被截掉。請注意:留言不可帶有網址,會被濾掉。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

[jQuery] 利用load()來達成ajax的寫法 jQuery中利用load()來達成ajax的寫法,也有人稱他是假的ajax,作法就是..

[jQuery] textarea 的取值和給值 HTML 的 TEXTAREA 標籤若要用 jquery 取值,不能使用 .text() 或 .html() ,使用 .

如何在linux下執行java 原生的java應用程式可以使用簡單的方法在console下面寫出來,適合作簡單的應用

[Freebsd] 定時測試 ADSL 是否斷線並重連 中華電信 ADSL 雖有固定 ip,可是他卻會不定時「斷線」, 使用以下的 方法可以定時測試是否斷線,以及重新撥接。

[札記] 2016.7~12月札記 札記,只是札記