티스토리 뷰
원하던 것은 특정 계정으로 불특정 다수가 영상을 업로드 하게 해주는 기능
웹상에 돌아다니는 소스들 중에 CI[코드이그나이터]로 작업된 소스가 있으나 oauth2.0이 아닌 1.1때 작업이라 쓸수가 없어서 우선 php로 된 소스 찾아서 적용 시켜봄..
다만 대부분의 소스에서 client.php와 service/youtube.php를 include해서 쓰게 해놨는데 이 파일들도 예전기준꺼로는 찾기가 좀 어려움..
찾는다고 해도 google_service라는 클래스를 상속받아서 쓰게 되있는데 이게 없....
https://developers.google.com/youtube/v3/code_samples/php?hl=ko
위 php코드 샘플에서도 두개 파일을 연결해서 작업하는걸로 되어있음.. 하지만 해당 파일은 git에 가보면 못찾음..
결론은 컴포저 통해서 google/apiclient:^2.0 설치하고
require_once '/path/to/google-api-php-client/vendor/autoload.php';
위처럼 컴포저 autoload.php 경로 땡겨와서 api관련 파일 한방에 처리
//에러 보기위한 설정
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
// 아래 client.php 대신에 apiclient:^2.0 설치 후 연결
require_once 'vendor/autoload.php';
//require_once 'Client.php';
//require_once 'ServiceYoutube.php';
// 리턴값 initialize
$code = true;
$data = "";
$error_msg = "";
// OAuth 2.0 Playgroud에서 받은 인증키 키 받는 방법은 하단에서 다시 설명
$key = file_get_contents('the_key.txt');
$keyFile = json_decode(file_get_contents('the_key.txt'),true);
// accessToken 갱신용
$refreshToken = $keyFile["refresh_token"];
// Google Developer Console에서 받은 OAuth 2.0 Client ID키
//이부분은 파일로 가져와도 되고 하단에 $client_id와 secret에 각각 값 입력해줘도 됨 파일받는 방법은 하단에 설명
$secret = json_decode(file_get_contents('client_secret.json'),true);
// Oauth2.0 Client ID의 이름 값과 일치해야 합니다
$application_name = 'GoogleLogin';
$client_id = $secret["web"]["client_id"];
$client_secret = $secret["web"]["client_secret"];
// 사용할 Youtube APIs
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner');
//업로드 파일 처리 시 form에서 만든 input name으로 변경.
//$file = $_FILES['input:file = name']['tmp_name'];
//테스트용
$file = $파일경로.'test.mp4';
$videoPath = $file;
// 비디오 설명, Youtube 내용부분에 들어갑니다
$videoDescription = "A high definition video tutorial";
// 비디오 제목, Youtube 제목부분에 들어갑니다
$videoTitle = "test video";
/*
// Video Category List
1: Film & Animation, 2: Autos & Vehicles, 10: Music, 15: Pets & Animals, 17: Sports,
18: Short Movies, 19: Travel & Events, 20: Gaming, 21: VideoBlogging, 22: People & Blogs,
23: Comedy, 24: Entertainment, 25: News & Politics, 26: Howto & Style, 27: Education,
28: Science & Technology, 29: Nonprofits & Activism, 30: Movies, 31: Anime/Animation, 32: Action/Adventure,
33: Classics, 34: Comedy, 35: Documentary, 36: Drama, 37: Family,
38: Foreign, 39: Horror, 40: Sci-Fi/Fantasy, 41: Thriller, 42: Shorts,
43: Shows, 44: Trailers
*/
$videoCategory = "27"; // #라이프스타일
// 비디오 태그
$videoTags = array("youtube", "test");
try{
$client = new Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
$client->setClientSecret($client_secret);
if ($client->getAccessToken()) {
// 토큰은 한시간마다 Expired 됩니다(고정값이라 변경이 불가능)
if($client->isAccessTokenExpired()) {
$newToken = json_encode($client->getAccessToken());
// 여기에 OAuth2.0 Playground에서 받은 Refresh_token을 넣어야합니다
$client->refreshToken($refreshToken);
// 새로 인증 받은 토큰을 key에 저장
file_put_contents('the_key.txt', json_encode($client->getAccessToken()));
}
// Youtube 객체 생성
$youtube = new Google_Service_YouTube($client);
// 설명 저장
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($videoTitle);
$snippet->setDescription($videoDescription);
$snippet->setCategoryId($videoCategory);
$snippet->setTags($videoTags);
// 비디오 공개여부 > public[공개], private[비공개], unlisted[미등록]
$status = new Google_Service_YouTube_VideoStatus();
$status->setPrivacyStatus('unlisted');
// 설명과 상태를 video에 저장
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// 조각 업로드의 사이즈를 변경, 높을수록 업로드 속도가 빨라지고 작을수록 better recovery 라는데
// 작을 수록 업로드 시간만 늘어나지, 화질에는 영향이 없었음
// Default : 1*1024*1024
$chunkSizeBytes = 1 * 1024 * 1024;
// 직접적으로 비디오를 올리는 부분
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// 업로드 성공시
if ($status->status['uploadStatus'] == 'uploaded') {
$code = true;
$data = $status->getId();
}else{
$code = false;
$error_msg = "youtube upload fail";
}
$client->setDefer(false);
} else{
$error_msg = 'Problems creating the client';
}
} catch(Google_Service_Exception $e) {
$error_msg = "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
}catch (Exception $e) {
$error_msg = "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage();
}
$data = array (
"code" => $code,
"data" => $data,
"error_msg" => $error_msg
);
echo json_encode($data);
the_key.txt 파일 생성 방법
https://developers.google.com/oauthplayground/
위 주소에서 step1에 youtube Data API v3 > https://www.googleapis.com/auth/youtube.upload
선택 후 Authorize APIs 클릭
로그인창 뜸 로그인 ㄱㄱ
youtube동영상관리 계정 액세스 허용 클릭
Authorization code:@#$@%$#%!@##@#$@#$#@ 이 보이고 하단에
Exchange authorization code for tokens 클릭하면
{
"access_token": "",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": ""
}
위 같은 json형식이 오른쪽 하단에 출력됨
이부분만 긁어서 the_key.txt 파일로 생성
client_secret.json파일 받는건
https://console.cloud.google.com/apis/credentials?folder&organizationId
위 페이지에서 Oauth 2.0 클라이언트 ID 제일 오른쪽에 다운로드 버튼 이용해서 받으시고 파일명 변경
API 사용을 위한 프로젝트 등록 및 사용자정보 관련된건 제외..
소스 참조 블로그 추소
'serverSide > PHP' 카테고리의 다른 글
[codeIgniter] Curl 헤더(header) 정보 추가 (0) | 2020.02.10 |
---|---|
[CI] 코드이그나이터 + MSSQL2008 다국어처리 (0) | 2019.04.30 |
[codeigniter]코드이그나이터 csrf 적용 안되게 하는 방법 (0) | 2018.07.25 |
코드이그나이터 MSSQL aJax Json (0) | 2017.05.11 |
[PHP] ICONV Detected an illegal character in input string (0) | 2017.05.10 |