简体   繁体   中英

How do you call Square's APIs to Google Sheets using Google Apps Script?

Hello. I'd appreciate any help in making a connection: Here's what I'm trying to 'Get' info from:

curl https://connect.squareup.com/v2/locations
-H 'Square-Version: 2022-01-20'
-H 'Authorization: Bearer ACCESS_TOKEN'
-H 'Content-Type: application/json'

Setting the Scopes: First I set the following scopes in the manifest file (here's a picture). I followed a similar notation as google's.

用于访问 Square api 的应用脚本清单

The Apps Script:

function squareLocations() {
  var url = "https://connect.squareup.com/v2/locations";
  var headers = {
    "contentType":"application/json",
    "headers": {"Square-Version": "2022-01-20",
                "Authorization": "Bearer <TOKEN>"}
                };
  var data = 
  { 
     'locations':
                {
                'id': locationID,
                'name': locationName,
                'address': locationAdress,
                }
  }
  var response = UrlFetchApp.fetch(url, headers);
  var text = response.getResponseCode();
  var json = JSON.parse(response.getContextText());
  Logger.log (text);
  Logger.log (json);
  
  
  }

response returns a 400 error: invalid scope (lists all scopes).

In the appsscript.json file remove the OAuth scope from square. On this file only include the OAuth scopes required by the Google Apps Script and Advanced Services (like Advanced Sheets Service).

The scopes of APIs called using by UrlFetchApp.fetch() might be included when generating the token or on the corresponding API console / App settings (I'm sorry, I don't know the details of Square API).

Background: why the manifest scopes are not relevant to the Square API##

The Square API uses the Oauth2 protocol . The idea of this protocol is as follows: you provide the user an opportunity to log in to their Square account, and in the process, you capture an oauth token that represents that user's login. This token allows your script to take action on the user's behalf. The scopes you specify tell the user what types of actions you'll be performing on their behalf, and you are limited to only those actions when calling the API.

The scopes listed in the Apps Script manifest represent the same idea, but for Google's services , not any external services like Square. When you call ScriptApp.getOauthToken() , you get a token for performing actions within the Google account of the user currently running the Apps Script script. (The reason you can do this for Google services without presenting a login screen is that the Google user has already logged in in order to run the script in the first place.)

But for any non-Google API like Square, you need to set up a full OAuth2 process, as detailed below:

The main question: How to access Square's API from Google Apps Script

There is an OAuth2 library for Apps Script that handles most of the mechanics of obtaining and storing the token for any API that uses OAuth2. Start by adding the library to your script (the library's script id is 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF ).

Then obtain the callback uri for your project. Do this by executing the following function from the script editor:

function logRedirectUri()
{
  console.log(
    OAuth2.getRedirectUri()
  )
}

Now go to the Square developer dashboard , and create a new application. There's an OAuth link on the left side of the app's main screen. Go to that link and you'll get the app's Application ID and Application Secret. You'll need those for your script. In addition, on this screen you should add the redirect uri you obtained above (when the user logs in to Square, the Square API will now know to redirect to this uri, which your script uses to record the oauth token).

Now you're ready to use the OAuth library to provide the Square sign-in process and then call the API. I've created a repo of the code I use for doing this, which you should be able to drop in to your script, but the relevant points are:

  1. In the getSquareService function, set SQUARE_CLIENT_ID and SQUARE_CLIENT_SECRET to the id and secret you got from the Square developer dashboard.

  2. getSquareService is also where you list the scopes you want for the Square API.

     function getSquareService() { var SQUARE_CLIENT_SECRET = '{your square application secret}' var SQUARE_CLIENT_ID = '{your square application id}' return OAuth2.createService('Square') // Set the endpoint URLs. .setAuthorizationBaseUrl('https://connect.squareup.com/oauth2/authorize').setTokenUrl('https://connect.squareup.com/oauth2/token') // Set the client ID and secret. .setClientId(SQUARE_CLIENT_ID).setClientSecret(SQUARE_CLIENT_SECRET) // Set the name of the callback function that should be invoked to // complete the OAuth flow. .setCallbackFunction('authCallbackSquare') // Set the property store where authorized tokens should be persisted. // Change this to.getUserProperties() if you are having multiple google users authorize the service: // this will prevent one user's token from being visible to others. .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scopes needed. For a full list see https://developer.squareup.com/docs/oauth-api/square-permissions.setScope( [ 'ORDERS_WRITE', 'PAYMENTS_WRITE', 'PAYMENTS_READ', 'ORDERS_READ', 'MERCHANT_PROFILE_READ' ].join(" ") ) // Set grant type.setGrantType('authorization_code') }

And include the callback function that will store the token:

function authCallbackSquare(request)
{
  var service = getSquareService();

  // Now process request
  var authorized = service.handleCallback(request);
  if (authorized)
  {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else
  {
    return HtmlService.createHtmlOutput('Denied. You can close this tab.');
  }
}
  1. If your script is bound to a spreadsheet, you can run authorizeSquareUser() in the repo to get a sidebar that initiates the authorization flow. Otherwise, run this modified version:

     function authorizeSquareUser() { var service = getSquareService(); var authorizationUrl = service.getAuthorizationUrl(); var template = HtmlService.createTemplateFromFile('square/auth-sidebar'); template.authorizationUrl = authorizationUrl; console.log("Auth URL is %s", authorizationUrl); }

and then visit the url that is logged. At this url you will log in to your square account, and then you should be redirected to a page that says "Success. You can close this tab."

At this point, the Square user's OAuth token has been stored in the script properties of your project. You are now ready to make a call to the Square API. When doing this, you access the stored token using getSquareService().getAccessToken() , so your headers will look like

var headers = {
  'Authorization': 'Bearer ' + getSquareService().getAccessToken(),
  'Square-Version': '2022-01-20',
  'Content-Type': 'application/json'
}

Then you can call

UrlFetchApp.fetch(url, {'method': 'GET', 'headers': headers}) // Change GET method depending on the action you are performing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM