본문 바로가기
기타

틱톡 API로 동영상 업로드하기 4 : 토큰 (PHP)

by zgabriel 2025. 12. 26.
728x90
반응형

Authorize Code 를 받았다면 그 다음 토큰을 받는건 간단하다.

 

아래 함수에 기존 정보를 입력하고 호출해주면 된다. (code는 유효기간이 짧아서 바로 호출)

 

문제는 토큰은 유효기간이 있는 정보이기 때문에 만료되면 재발급해야되는데

 

다행히 code 부터 발급받는게 아닌 리플레시토큰을 사용해 재발급받으면 된다.

 

리플레시 토큰의 유효기간은 한달정도되는데 이것까지 만료되면 아마도 코드값부터

 

새로 발급받아야 할것이기 때문에 잘 관리해야한다. 

 

-> 토큰 유효기간 1일 

 

function getToken($client_key, $client_secret, $redirect_uri, $code){
     $url = "https://open.tiktokapis.com/v2/oauth/token/";

      $post_data = [
            'client_key'    => $client_key,
            'client_secret' => $client_secret,
            'code'          => $code,
            'grant_type'    => 'authorization_code',
            'redirect_uri'  => $redirect_uri
      ];

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
             'Cache-Control: no-cache'
      ]);

       $response = curl_exec($ch);
       $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

       if (curl_errno($ch)) {
              echo 'Curl error: ' . curl_error($ch);
       }

       $result = json_decode($response, true);
       curl_close($ch);

       if ($http_code === 200 && !isset($result['error'])) {
              //발급성공 - array ('access_token', 'refresh_token', 'open_id') 
              return $result;   
       } else {
              // 실패 
              return false;
        }
}

 

728x90
반응형