카테고리 없음

[Twitter] account/verify_credentials API 를 사용한 사용자 정보 받아오기.

사악미소 2016. 5. 27. 10:36
반응형

참고 : https://opentutorials.org/module/53/859





■ 전체 데이터 불러오기



01. 이전 포스팅에서 생성한 twitter_request_token.php의 소스 중 콜백될 URL을 아래와 같은 경로로 직접 수정해 두도록 한다.

 twitter_request_token.php

<?php
session_start();

// library 로드, 변수 설정 등
require_once("./lib/twitteroauth.php");
$consumer_key = "LX9ewAqZj76gKB0JeCtBTLrvq";
$consumer_secret = "g80L73N8SaUZGjn4Bzbit0wYbYzLOmeBytZ8jG7GHwK0BtNhZf";

// TwitterOAuth object 생성
$connection = new TwitterOAuth($consumer_key, $consumer_secret);

// request token 발급
// $request_token = $connection->getRequestToken();


// 지난 소스와 달리 직접 콜백될 URL을 직접 지정해 주었다.
$domain = "http://" . $_SERVER['HTTP_HOST'] . "/";
$request_token = $connection->getRequestToken($domain . "twitter/twitter_example.php");
 
// 결과 확인
switch($connection -> http_code) {

    case 200 :

        // 성공, token 저장
        $_SESSION['oauth_token'] = $token = $request_token['oauth_token'];           // 토큰 KEY
        $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];      // 토큰 시크릿 KEY
 
        // 인증 url 확인
        $url = $connection->getAuthorizeURL($token);
 
        // 인증 url (로그인 url) 로 redirect
        header("Location: " . $url);

    break;
 
    default:

        echo "Could not connect to Twitter. Refresh the page or try again later.";

    break;
}
?>




02. 콜백될 파일을 만들고 account/verify_credentials 을 사용하여 사용자 정보를 받아온다.

 twitter_example.php

<?php
// Access token 을 포함한 TwitterOauth Object 생성
session_start();

// library 로드, 변수 설정 등
require_once("./lib/twitteroauth.php");
$consumer_key = "LX9ewAqZj76gKB0JeCtBTLrvq";
$consumer_secret = "g80L73N8SaUZGjn4Bzbit0wYbYzLOmeBytZ8jG7GHwK0BtNhZf";

// Access token 을 포함한 TwitterOAuth object 생성
$connection = new TwitterOAuth($consumer_key, $consumer_secret, 토큰 KEY, 토큰 시크릿 KEY);

// get user profile
$user = $connection->get("account/verify_credentials");

echo "<pre>";
print_r($user);
echo "</pre>";
?>




03. 출력결과







데이터 분리해서 출력하기



01. 오브젝트 형태로 가져온 데이터는 아래와 같은형태로 개별적으로 출력할 수 있다.

 twitter_example.php

<?php
// Access token 을 포함한 TwitterOauth Object 생성
session_start();

// library 로드, 변수 설정 등
require_once("./lib/twitteroauth.php");
$consumer_key = "LX9ewAqZj76gKB0JeCtBTLrvq";
$consumer_secret = "g80L73N8SaUZGjn4Bzbit0wYbYzLOmeBytZ8jG7GHwK0BtNhZf";

// Access token 을 포함한 TwitterOAuth object 생성
$connection = new TwitterOAuth($consumer_key, $consumer_secret, 토큰 KEY 토큰 시크릿 KEY);

// get user profile
$user = $connection->get("account/verify_credentials");

echo $user->name;
echo "<br/>";
echo $user->screen_name;
echo "<br/>";
echo "<img src='" . $user->profile_image_url . "'/>";
?>




02. 출력결과

※ 사용자 닉네임과 트위터 아이디 프로필 사진을 불러오는 것을 확인 할 수있다.



반응형