NAVER
[ class tree: NAVER ] [ index: NAVER ] [ all elements ]

Source for file NAVER.php

Documentation is available at NAVER.php

  1. <?php
  2. /**
  3.  * Project: NAVER :: 네이버 로그인(oauth2) pear package<br>
  4.  * File:    NAVER.php<br>
  5.  * Dependency:
  6.  *   - {@link http://pear.oops.org/docs/li_HTTPRelay.html oops/HTTPRelay}
  7.  *   - {@link http://pear.oops.org/docs/li_myException.html oops/myException}
  8.  *   - {@link http://kr1.php.net/manual/en/book.curl.php curl extension}
  9.  *
  10.  * oops/NAVER pear package는
  11.  * {@link http://developer.naver.com/wiki/pages/NaverLogin 네이버 아이디로 로그인}
  12.  * 을 pear package로 구현을 한 것이다.
  13.  *
  14.  * {@link http://developer.naver.com/wiki/pages/NaverLogin 네이버 아이디로 로그인}
  15.  * {@link http://developer.naver.com/wiki/pages/OAuth2 네이버 OAuth}와는 다른 API로서
  16.  * 로그인 사용자의 개인 식별 정보를 활용할 수 있으며, OAuth2 방식으로 구현이 되어있다.
  17.  *
  18.  * 이 package를 사용하기 위해서는 먼저 Naver에서 ClientID와 ClientSecret을 발급받아야
  19.  * 한다. http://developer.naver.com/wiki/pages/NaverLogin 를 참고하라.
  20.  *
  21.  * !!참고
  22.  * oops/NAVER pear package는 더이상 개발되지 않습니다.
  23.  * {@link http://pear.oops.org/docs/li_oops-OAUTH2.html oops/OAUTH2 package}
  24.  * 사용하시기 바랍니다.
  25.  *
  26.  * @category  HTTP
  27.  * @package   NAVER
  28.  * @author    JoungKyun.Kim <http://oops.org>
  29.  * @copyright (c) 2018, OOPS.org
  30.  * @license   BSD License
  31.  * @link      http://pear.oops.org/package/NAVER
  32.  * @since     File available since release 1.0.0
  33.  * @example   NAVER/tests/test.php NAVER pear package 예제 코드
  34.  * @filesource
  35.  */
  36.  
  37. /**
  38.  * import HTTPRelay class
  39.  */
  40. require_once 'HTTPRelay.php';
  41.  
  42.  
  43. /**
  44.  * Naver pear pcakge의 main class
  45.  *
  46.  * OAuth2를 이용하여 네이버 로그인을 진행하고, 로그인된 사용자의
  47.  * 정보를 얻어온다.
  48.  *
  49.  * !!참고
  50.  * oops/NAVER pear package는 더이상 개발되지 않습니다.
  51.  * {@link http://pear.oops.org/docs/li_oops-OAUTH2.html oops/OAUTH2 package}
  52.  * 사용하시기 바랍니다.
  53.  *
  54.  * @package NAVER
  55.  * @author    JoungKyun.Kim <http://oops.org>
  56.  * @copyright (c) 2018, OOPS.org
  57.  * @license   BSD License
  58.  * @link      http://pear.oops.org/package/NAVER
  59.  * @since     File available since release 1.0.0
  60.  * @example   NAVER/tests/test.php NAVER pear 예제 코드
  61.  */
  62. Class NAVER {
  63.     // {{{ properities
  64.     /**#@+
  65.      * @access private
  66.      */
  67.     /**
  68.      * 세션 이름
  69.      * @var string 
  70.      */
  71.     private $sessid   'NaverOauth';
  72.     /**
  73.      * login url
  74.      * @var string 
  75.      */
  76.     private $reqAuth  'https://nid.naver.com/oauth2.0/authorize';
  77.     /**
  78.      * token url
  79.      * @var string 
  80.      */
  81.     private $reqToken 'https://nid.naver.com/oauth2.0/token';
  82.     /**
  83.      * user information url
  84.      * @var string 
  85.      */
  86.     private $reqUser  'https://apis.naver.com/nidlogin/nid/getUserProfile.xml';
  87.     /**
  88.      * consumer information
  89.      * @var stdClass memebr는 다음과 같음
  90.      *    - id     : Naver login CliendID key
  91.      *    - secret : Naver login ClientSecret key
  92.      *    - callback : 이 class를 호출하는 페이지
  93.      */
  94.     private $consumer;
  95.     /**#@-*/
  96.     /**
  97.      * 네이버 로그인에 필요한 session 값
  98.      * @access public
  99.      * @var stdClass 
  100.      */
  101.     public $sess;
  102.     // }}}
  103.  
  104.     // {{{ +-- public (void) __construct ($v)
  105.     /**
  106.      * Naver 로그인 인증 과정을 수행한다. 인증 과정 중에
  107.      * 에러가 발생하면 myException 으로 에러 메시지를
  108.      * 보낸다.
  109.      *
  110.      * @access public
  111.      * @param stdClass $v 
  112.      *    - id       발급받은 Naver login ClientID key
  113.      *    - secret   발급받은 Naver login ClientScret key
  114.      *    - callback 이 클래스가 호출되는 url
  115.      * @return void 
  116.      */
  117.     function __construct ($v{
  118.         if isset ($_SESSION[$this->sessid]) ) {
  119.             $_SESSION[$this->sessidnew stdClass;
  120.             $_SESSION[$this->sessid]->appId = (object) $v;
  121.         }
  122.         $this->sess = &$_SESSION[$this->sessid];
  123.         $this->consumer = (object) $v;
  124.  
  125.         if isset ($_GET['logout']) ) {
  126.             $this->reqLogout ();
  127.             return;
  128.         }
  129.  
  130.         $this->checkError ();
  131.         $this->reqLogin ();
  132.         $this->reqAccessToken ();
  133.     }
  134.     // }}}
  135.  
  136.     // {{{ +-- private (string) mkToken (void)
  137.     /**
  138.      * 세션 유지를 위한 token 값
  139.      *
  140.      * @access private
  141.      * @return string 
  142.      */
  143.     private function mkToken ({
  144.         $mt microtime ();
  145.         $rand mt_rand ();
  146.         return md5 ($mt $rand);
  147.     }
  148.     // }}}
  149.  
  150.     // {{{ +-- private (void) reqLogin (void)
  151.     /**
  152.      * 로그인 창으로 redirect
  153.      *
  154.      * @access private
  155.      * @return void 
  156.      */
  157.     private function reqLogin ({
  158.         $cons &$this->consumer;
  159.         $this->sess->state $this->mkToken ();
  160.  
  161.         if $_GET['code'|| isset ($this->sess->oauth)  )
  162.             return;
  163.  
  164.         $url sprintf (
  165.             '%s?client_id=%s&response_type=code&redirect_uri=%s&state=%s',
  166.             $this->reqAuth$cons->idrawurlencode ($cons->callback),
  167.             $this->sess->state
  168.         );
  169.  
  170.         Header ('Location: ' $url);
  171.         exit;
  172.     }
  173.     // }}}
  174.  
  175.     // {{{ +-- private (void) reqAccessToken (void)
  176.     /**
  177.      * Authorization code를 발급받아 session에 등록
  178.      *
  179.      * NAVER::$sess->oauth 를 stdClass로 생성하고 다음의
  180.      * member를 등록한다.
  181.      *
  182.      *   - access_token:      발급받은 access token. expires_in(초) 이후 만료
  183.      *   - refresh_token:     access token 만료시 재발급 키 (14일 expire)
  184.      *   - token_type:        Bearer or MAC
  185.      *   - expires_in:        access token 유효시간(초)
  186.      *   - error:             error code
  187.      *   - error_description: error 상세값
  188.      *
  189.      * @access private
  190.      * @return void 
  191.      */
  192.     private function reqAccessToken ({
  193.         $sess &$this->sess;
  194.         $cons &$this->consumer;
  195.  
  196.         if $_GET['code'|| isset ($sess->oauth) )
  197.             return;
  198.  
  199.         $url sprintf (
  200.             '%s?client_id=%s&client_secret=%s&grant_type=authorization_code&state=%s&code=%s',
  201.             $this->reqToken$cons->id$cons->secret$sess->state$_GET['code']
  202.         );
  203.  
  204.         $http new HTTPRelay;
  205.         $buf $http->fetch ($url);
  206.         $r json_decode ($buf);
  207.  
  208.         if $r->error )
  209.             $this->error ($r->error_description);
  210.         
  211.         $sess->oauth = (object) $r;
  212.     }
  213.     // }}}
  214.  
  215.     // {{{ +-- private (void) checkError (void)
  216.     /**
  217.      * 에러 코드가 존재하면 에러 처리를 한다.
  218.      *
  219.      * @access private
  220.      * @return void 
  221.      */
  222.     private function checkError ({
  223.         $sess &$this->sess;
  224.  
  225.         if $_GET['error')
  226.             $this->error ($_GET['error_description']);
  227.  
  228.         if $_GET['state'&& $_GET['state'!= $sess->state )
  229.             $this->error ('Invalude Session state: ' $_GET['state']);
  230.     }
  231.     // }}}
  232.  
  233.     // {{{ +-- private (void) error ($msg)
  234.     /**
  235.      * 에러를 Exception 처리한다.
  236.      *
  237.      * @access private
  238.      * @return void 
  239.      */
  240.     private function error ($msg{
  241.         $msg $_SERVER['HTTP_REFERER'"\n" $msg;
  242.         throw new myException ($msgE_USER_ERROR);
  243.     }
  244.     // }}}
  245.  
  246.     // {{{ +-- public (stdClass) getUser (void)
  247.     /**
  248.      * 로그인 과정이 완료되면 발급받은 NAVER::$sess->oauth 에 등록된
  249.      * 키를 이용하여 로그인 사용자의 정보를 가져온다.
  250.      *
  251.      * @access public
  252.      * @return stdClass 다음의 object를 반환
  253.      *    - id       사용자 확인 값
  254.      *    - nickname 사용자 닉네임
  255.      *    - email    이메일(ID@naver.com)
  256.      *    - gender   성별 (F:여성/M:남성/U:확인불가)
  257.      *    - birth    생일 (MM-DD 형식으로 반환)
  258.      *    - img      프로필 사진 URL 정보
  259.      */
  260.     public function getUser ({
  261.         $sess &$this->sess;
  262.  
  263.         if isset ($sess->oauth) )
  264.             return false;
  265.  
  266.         $req $sess->oauth->token_type ' ' $sess->oauth->access_token;
  267.  
  268.         $header array ('Authorization' => $req);
  269.         $http new HTTPRelay ($header);
  270.         $buf $http->fetch ($this->reqUser);
  271.  
  272.         $xml simplexml_load_string ($buf);
  273.         if $xml->result->resultcode != '00' )
  274.             $this->error ($r->result->message);
  275.  
  276.         $xmlr &$xml->response;
  277.         $r array (
  278.             'id' => (string) $xmlr->enc_id->{0},
  279.             'name' => (string) $xmlr->nickname->{0},
  280.             'email' => (string) $xmlr->email->{0},
  281.             'gender' => (string) $xmlr->gender->{0},
  282.             'age'   => (string) $xmlr->age->{0},
  283.             'birth' => (string) $xmlr->birthday,
  284.             'img'  => (string) $xmlr->profile_image
  285.         );
  286.  
  287.         return (object) $r;
  288.     }
  289.     // }}}
  290.  
  291.     // {{{ +-- public (void) reqLogout (void)
  292.     /**
  293.      * 네이버 로그인의 authorization key를 만료 시키고
  294.      * 세션에 등록된 정보(NAVER::$sess)를 제거한다.
  295.      *
  296.      * @access public
  297.      * @return void 
  298.      */
  299.     public function reqLogout ({
  300.         $sess &$this->sess;
  301.         $cons &$this->consumer;
  302.  
  303.         if isset ($sess->oauth) )
  304.             return;
  305.  
  306.         // guide에는 refresh_token을 넣으라고 되어 있는데,
  307.         // 실제로는 access_token을 넣어야 한다.
  308.         $url sprintf (
  309.             '%s?grant_type=delete&client_id=%s&client_secret=%s&' .
  310.             'access_token=%s&service_provider=NAVER',
  311.             $this->reqToken$cons->id$cons->secret$sess->oauth->access_token
  312.         );
  313.  
  314.         $http new HTTPRelay;
  315.         $buf $http->fetch ($url);
  316.  
  317.         $r json_decode ($buf);
  318.         if $r->error )
  319.             $this->error ($r->error_description);
  320.  
  321.         unset ($_SESSION[$this->sessid]);
  322.     }
  323.     // }}}
  324. }
  325.  
  326. /*
  327.  * Local variables:
  328.  * tab-width: 4
  329.  * c-basic-offset: 4
  330.  * End:
  331.  * vim600: noet sw=4 ts=4 fdm=marker
  332.  * vim<600: noet sw=4 ts=4
  333.  */
  334. ?>

Documentation generated on Tue, 14 May 2019 02:00:40 +0900 by phpDocumentor 1.4.4