如何使用Google Apps脚本调用Smartsheet API?

时间:2016-04-10 10:52:59

标签: google-apps-script smartsheet-api

我使用Postman和Charles查看我的Smartsheet GET函数是否有效,并且一切正常,我将数据返回json字符串。

我尝试从本地代码和Google应用脚本html页面运行调用。

但是我从Google应用脚本页面收到此错误:

“XMLHttpRequest无法加载https://api.smartsheet.com/2.0/sheets/ MY SMART SHEET ID。对预检请求的响应未通过访问控制检查:请求的资源上没有”Access-Control-Allow-Origin“标头。来源'{因此,{3}}'不允许访问。“

我的目标是从Smartsheet表自动更新Google表格。

我的Ajax请求如下所示:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.smartsheet.com/2.0/sheets/SHEET_ID",
  "method": "GET",
  "headers": {
    "authorization": "Bearer MY_SECRET_ACCESS_TOKEN",
    "cache-control": "no-cache",
    "postman-token": "SOME_LONG_TOKEN"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

1 个答案:

答案 0 :(得分:2)

无法从客户端JavaScript调用Smartsheet API,因为此时API并不支持CORS

可以直接从Google Apps脚本调用Smartsheet API。事实上,我们/ Smartsheet发布了两个Google插件,这两个插件都使用脚本中的Smartsheet API(12)。

Google apps-script-oauth2 project提供了在GitHub上的示例目录中使用Smartsheet API的完整示例。请参阅samples/Smartsheet.gs

将OAuth令牌放在一边,您可以像这样向Smartsheet API发出请求:

var url = 'https://api.smartsheet.com/2.0/users/me';
var options = {
  'method': 'get'
  , 'headers': {"Authorization": "Bearer " + getSmartsheetService().getAccessToken()  }
};
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log("email:" + JSON.parse(response).email);

请注意,上述示例中的getSmartsheetService()与Google自述文件中的getDriveService()类似,但Smartsheet除外。完整代码如下:

function getSmartsheetService() {
    // Create a new service with the given name. The name will be used when
    // persisting the authorized token, so ensure it is unique within the
    // scope of the property store.
    return OAuth2.createService('scott_smartsheet')

        // Set the endpoint URLs, which are the same for all Google services.
        .setAuthorizationBaseUrl('https://app.smartsheet.com/b/authorize')
        .setTokenUrl('https://api.smartsheet.com/2.0/token')

        // Set the client ID and secret, from the Google Developers Console.
        .setClientId(SMARTSHEET_CLIENT_ID)
        .setClientSecret(SMARTSHEET_CLIENT_SECRET)

        // Set the name of the callback function in the script referenced
        // above that should be invoked to complete the OAuth flow.
        .setCallbackFunction('authCallback')

        // Set the property store where authorized tokens should be persisted.
        .setPropertyStore(PropertiesService.getUserProperties())

        // Set the scopes to request (space-separated for Google services).
        .setScope('READ_SHEETS')

        // Set the handler for adding Smartsheet's required SHA hash parameter to the payload:
        .setTokenPayloadHandler(smartsheetTokenHandler)
        ;
}