Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active October 26, 2020 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhawksey/4516282ed10e40d505addd88266ad805 to your computer and use it in GitHub Desktop.
Save mhawksey/4516282ed10e40d505addd88266ad805 to your computer and use it in GitHub Desktop.
YouTube service setup for use with OAuth2 for Apps Script https://github.com/googlesamples/apps-script-oauth2
/* Setup
1. In the Script Editor select Resources > Cloud platform project... and click the link to the currently associated project
2. In the Google Cloud Platform window click "Go to APIs overview"
3. In APIs & services click "Enable APIs and Services"
4. In the Library search/click on YouTube Data API and click 'Enable'
5. Still in the APIs & services screen click on Credentials from the side menu
6. Click the 'Create credentials', select 'OAuth Client ID' then 'Web application'
7. Enter a name as required and in the 'Authorised JavaScript origins' enter https://script.google.com
8. In this script project Run > Run function > logRedirectUri. From the View > Logs copy the url into the 'Authorised redirect URIs' field API console, click 'Create'
9. In this script project open File > Project properties and in the Script properties tab and new rows for client_id and client_secret copying the values from the API console
10. In this script project Run> Run function > setup and and then from the View > Logs copy the url in a new browser tab. Select the YouTube account you would like to use with this script project
*/
/**
* Authorizes and makes a request to the YouTube API.
*/
function setup() {
var service = getYouTubeService();
YouTube.setTokenService(function(){ return service.getAccessToken(); });
if (service.hasAccess()) {
var result = YouTube.channelsList("snippet", {mine:true});
Logger.log(JSON.stringify(result, null, 2));
throw "Open View > Logs to see result";
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
throw "Open View > Logs to get authentication url";
}
}
/**
* Configures the service.
*/
function getYouTubeService() {
return OAuth2.createService('YouTube')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret.
.setClientId(getStaticScriptProperty_('client_id'))
.setClientSecret(getStaticScriptProperty_('client_secret'))
// Set the name of the callback function that should be invoked to complete
// the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted
// you might want to switch to Script Properties if sharing access
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scope and additional Google-specific parameters.
.setScope(["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner",
"https://www.googleapis.com/auth/youtubepartner-channel-audit"])
.setParam('access_type', 'offline');
}
/**
* Handles the OAuth callback.
*/
function authCallback(request) {
var service = getYouTubeService();
var authorized = service.handleCallback(request);
if (authorized) {
return HtmlService.createHtmlOutput('Success!');
} else {
return HtmlService.createHtmlOutput('Denied');
}
}
/**
* Logs the redirect URI to register in the Google Developers Console.
*/
function logRedirectUri() {
var service = getYouTubeService();
Logger.log(service.getRedirectUri());
throw "Open View > Logs to get redirect url";
}
/**
* Reset the authorization state, so that it can be re-tested.
*/
function reset() {
var service = getYouTubeService();
service.reset();
}
/**
* Gets a static script property, using long term caching.
* @param {string} key The property key.
* @returns {string} The property value.
*/
function getStaticScriptProperty_(key) {
var value = CacheService.getScriptCache().get(key);
if (!value) {
value = PropertiesService.getScriptProperties().getProperty(key);
CacheService.getScriptCache().put(key, value, 21600);
}
return value;
}
@studiosimply
Copy link

TypeError: Function setTokenService not found on object AdvancedServiceIdentifier {name = youtube, version = v3}

@MauroRomanella
Copy link

line 30: YouTube.setTokenService(function(){ return service.getAccessToken(); });

ReferenceError: YouTube is not defined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment