2013-03-27 4 views
4

YouTube 동영상에 댓글을 게시하려고합니다 ...이를 위해 YouTube API를 사용합니다. 여기에 코드입니다 : 그 개인 물건을 숨기기 위해 참조CURL 요청이 작동하지 않는 이유는 무엇입니까?

<?php 
$message="Just Some Comment..."; 
$developer_key="<!---visit demo for actual code---!>"; 
$access_token=$_GET['code']; 
if(!$access_token){ Header("Location: <!---visit demo for actual code---!>");} 
$video_id="I3LMKhu2-vo"; 
$message_xml='<?xml version="1.0" encoding="UTF-8"?> 
<entry xmlns="http://www.w3.org/2005/Atom"  xmlns:yt="http://gdata.youtube.com/schemas/2007"> 
<content>' . $message . '</content> 
</entry>'; 
$url = "http://gdata.youtube.com/feeds/api/videos/" . $video_id . "/comments"; 
$header = array('Content-Type: application/atom+xml', 'Content-Length: ' . strlen($message_xml), 'Authorization: Bearer "' . $access_token . '"', 'GData-Version: 2', 'X-GData-Key: key=' . $developer_key); 
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "$message_xml"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$result = curl_exec($ch); 
echo curl_error($ch); 
curl_close($ch); 
echo $access_token; 
?> 

,하지만 당신은 그래서 제 질문은, 왜 댓글이 비디오에 나타나지 않음 votm.net78.net 에서 데모를 볼 수 있습니다, 사용자가 승인 토큰을 보냈지 만? 이 문제에 대해 도움을받을 수 있습니까? 감사!

+0

''$ result'에 무엇이 있습니까? '$ result = curl_exec ($ ch);'뒤에'var_dump ($ result);를 넣으면 어떻게 될까요? –

답변

2

실종 코드의 핵심은 토큰 서비스를 호출하여 실제 access_token을 가져 오기 위해 인증 코드를 사용해야한다는 것입니다 (내 코드의 2 단계 참조). 즉, 두 개의 컬 요청이있을 것입니다. https://developers.google.com/accounts/docs/OAuth2WebServer?hl=de#handlingtheresponse

는 또한, 당신은 (아직 수행하지 않은 경우) 공인 API 액세스에 대한 Client IDClient secret을 만들 https://code.google.com/apis/console/에 프로젝트를 생성해야합니다 자세한 내용은 문서를 보라. developer key 외에도이 작업이 필요합니다.

추가로 오류 검사를 통해 다음 코드를 작성하여 성공적으로 테스트했습니다. 자신의 구글 계정에와 댓글이 요구 사항을 게시됩니다 누가 대신 로그온 사용자가 연결된 가지고 있음을

<?php 

$developer_key='<!---hidden---!>'; 
$client_id=  '<!---hidden---!>'; 
$client_secret='<!---hidden---!>'; 

// error checking; user might have denied access 
if (isset($_GET['error'])) { 
    if ($_GET['error'] == 'access_denied') { 
     echo('You have denied access. Click <a href="'. $_SERVER["SCRIPT_NAME"] .'">here</a> to retry&hellip;'); 
    } else { 
     echo("An error has occurred: ". $_GET['error']); 
    } 
    exit; 
} 

// Step 1: redirect to google account login if necessary 
if(!isset($_GET['code']) || $_GET['code'] === '') { 
    Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id . 
      '&redirect_uri=http%3A%2F%2Flocalhost%2Fyoutube.php' . 
      '&scope=https://gdata.youtube.com&response_type=code&access_type=offline', 
     true, 307); 
    exit; 
} 
$authorization_code= $_GET['code']; 

// Step 2: use authorization code to get access token 
$url = "https://accounts.google.com/o/oauth2/token"; 
$message_post= 'code='. $authorization_code . 
     '&client_id='. $client_id . 
     '&client_secret='. $client_secret . 
     '&redirect_uri=http://localhost/youtube.php' . 
     '&grant_type=authorization_code'; 

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$result = curl_exec($ch); 

if ($cur_error= curl_error($ch)) { 
    echo($cur_error); 
    curl_close($ch); 
    exit; 
} 
curl_close($ch); 

$jsonArray= json_decode($result, true); 

if ($jsonArray === null) { 
    echo("Could not decode JSON."); 
    exit; 
} 

if (isset($jsonArray['error'])) { 
    echo("An error has occurred: ". $jsonArray['error']); 
    exit; 
} 

if (!isset($jsonArray['access_token'])) { 
    echo("Access token not found."); 
    exit; 
} 

// Step 3: using access_token for youtube api call 
$message="Just Some Comment..."; 
$access_token= $jsonArray['access_token']; 
$video_id="I3LMKhu2-vo"; 
$message_xml='<?xml version="1.0" encoding="UTF-8"?> 
<entry xmlns="http://www.w3.org/2005/Atom"  xmlns:yt="http://gdata.youtube.com/schemas/2007"> 
<content>' . $message . '</content> 
</entry>'; 
$url = "https://gdata.youtube.com/feeds/api/videos/" . $video_id . "/comments"; 
$header = array('Content-Type: application/atom+xml', 'Content-Length: ' . strlen($message_xml), 'Authorization: Bearer "' . $access_token . '"', 'GData-Version: 2.1', 'X-GData-Key: key=' . $developer_key); 
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_xml); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$result = curl_exec($ch); 
echo curl_error($ch); 
curl_close($ch); 

echo "DONE! Token:" . $access_token . "<br />\n"; 
var_dump($result); 
?> 

참고 : 나는 스크립트가 URL

http://localhost/youtube.php 

를 통해 액세스 할 수 있다고 가정 YouTube 계정 (Google 계정만으로는 충분하지 않음). 게다가 그는 YouTube에 적어도 하나의 댓글을 성공적으로 게시해야합니다. 그렇지 않으면 'youtube_signup_required'또는 'NoLinkedYouTubeAccount'와 같은 오류가 표시됩니다.

최근에 API 2.1 (GData-Version)으로 전환했으며 연결되지 않은 Google 계정의 경우 더 나은 기능과 오류보고 기능을 제공합니다.

+0

안녕하세요 고마워요! "Header는 둘 이상의 줄을 가질 수 없습니다"라는 오류가있어서 하나 또는 두 줄을 편집해야했지만 해결되었습니다! +50 담당자가 당신의 도움이됩니다. – InfiniDaZa

+0

여러분을 환영합니다! 나는 그것을 기쁘게 생각합니다, 담당자에게 감사드립니다 :) – Marcellus

관련 문제