admin管理员组

文章数量:1387410

Authentication Setup This section initializes the OAuth2 service for authenticating with the GTM API. The getOAuthService function sets up the OAuth2 flow by defining the authorization base URL, token URL, client ID, client secret, scope, and redirect URI.

// Replace these values with your own credentials
var CLIENT_ID = 'my client id goes here';
var CLIENT_SECRET = 'my client secret goes here';
var SCOPE = '.edit.containers';
var REDIRECT_URI = 'my redirect uri goes here';

// Initialize OAuth2 service
function getOAuthService() {
  return OAuth2.createService('GTM_API')
    .setAuthorizationBaseUrl('')
    .setTokenUrl('')
    .setClientId(CLIENT_ID)
    .setClientSecret(CLIENT_SECRET)
    .setScope(SCOPE)
    .setRedirectUri(REDIRECT_URI)
    .setCallbackFunction('doGet');  // Ensure this is set to 'doGet'
}

Handling OAuth2 Callback The doGet function handles the callback from Google's OAuth2 authorization process. When the user grants permission, this function confirms the authorization status and displays a message accordingly.

function doGet(e) {
  var service = getOAuthService(); // Get the OAuth2 service object
  var authorized = service.handleCallback(e); // Handle the callback

  if (authorized) {
    Logger.log('Authorization successful');
    return HtmlService.createHtmlOutput('Authorization successful! You can close this window.');
  } else {
    Logger.log('Authorization failed');
    return HtmlService.createHtmlOutput('Authorization failed. Please try again.');
  }
}

// Redirect the user to the OAuth2 consent page
function authorize() {
  var service = getOAuthService();
  Logger.log("Checking if we have access...");

  if (!service.hasAccess()) {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Authorization is needed. Visit this URL to authorize: %s', authorizationUrl);
    return;  // Do not proceed until authorized
  } else {
    Logger.log('Authorization successful!');
    createGTMVariable();  // Proceed to create GTM Variable if already authorized
  }
}

Creating the GTM Variable: This function attempts to create a variable within the specified GTM container using the access token retrieved via OAuth2.

function createGTMVariable() {
  var accountId = 'account id goes here'; // Replace with your GTM Account ID
  var containerId = 'container id goes here'; // Replace with your GTM Container ID
  var workspaceId = 'workspace id goes here'; // Hardcoded Workspace ID

  var variableName = 'cookie_user_id'; // Name of the variable
  var variableType = 'first_party_cookie'; // Type of the variable
  var variableValue = 'user_id'; // Value or the key used in the variable

  // Get OAuth2 token
  var service = getOAuthService();
  if (!service.hasAccess()) {
    Logger.log('Authorization required. Run the "authorize" function.');
    return;
  }

  var accessToken = service.getAccessToken();
  Logger.log('Access Token: ' + accessToken);  // Log the access token to check if it's correctly retrieved

  // Define the URL to create a variable in GTM workspace
  var url = '/' + accountId + '/containers/' + containerId + '/workspaces/' + workspaceId + '/variables';

  // Construct the payload with hardcoded details
  var payload = JSON.stringify({
    'name': variableName,
    'type': variableType,
    'parameter': [{
      'key': 'cookie_name',  // For 'first_party_cookie' type, the key should be 'cookie_name'
      'value': variableValue  // This is the value we pass (cookie_name as user_id)
    }]
  });

  // Options for the API request
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': payload,
    'headers': {
      'Authorization': 'Bearer ' + accessToken
    },
    'muteHttpExceptions': true // Allow logging of the full error response
  };

  try {
    // Make the API request to create the variable
    var response = UrlFetchApp.fetch(url, options);
    Logger.log('Created variable: ' + variableName);
    Logger.log('API Response: ' + response.getContentText()); // Log the response from the API
    return response.getContentText();  // Explicitly return the API response to show completion
  } catch (e) {
    Logger.log('Error creating variable: ' + variableName + ' Error: ' + e.message);
    Logger.log('Full Response: ' + e.response.getContentText()); // Log the full response from the API
    return 'Error: ' + e.message; // Explicitly return error message
  }
}

本文标签: