Weston
Weston

Reputation: 169

Receiving a 401 'truncated server' error when trying to add a Stripe API Key to UrlFetchApp in Google Apps Scripts

I'm trying to retrieve an invoice in Google Sheets via the Stripe API and I'm using Google Apps Scripts to run my code. Here's the code I have:

function callNumbers() 
  {
    var url = "https://api.stripe.com/v1/invoices/[unique_id]";
    var apiKey = "[api-key]";

    var response = UrlFetchApp.fetch(url, {"headers":{"[api-key]":apiKey}}); 
    var content = response.getContentText(); 
    Logger.log(response); 
    Logger.log(content);
 }

The Stripe invoice URL has a unique ID in the url above after /invoices/, representing the specific test invoice I want to retrieve.

I'm using a test Stripe API key, which begins with this before the unique API key code: sk_test_

The reference on the Stripe page looks like this:

curl https://api.stripe.com/v1/invoices/[unique_id] \
  -u sk_test_[api-key]:

The error message I receive looks like this:

Request failed for https://api.stripe.com/v1/invoices/[unique_id] returned code 401. Truncated server response: { "error": { "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g... (use muteHttpExceptions option to examine full response) (line 13, file "Code")

I'm not sure what's wrong with my code. I'm guessing it's something with the "headers" section but I don't know enough about APIs to know for sure. I'm using this test project in attempt to learn more about APIs.

Upvotes: 0

Views: 2188

Answers (1)

Alan Wells
Alan Wells

Reputation: 31310

Try something like this:

function getInvoiceObj(invoiceURL) {
  var content,options,response ,secret,url;

  secret = 'sk_test_ABC123';//sk_live_ABC123'

  url = "https://api.stripe.com/v1/invoices/" + invoiceURL;

  options = {
    "method" : "GET",
    "headers": {
      "Authorization": "Bearer " + secret
    },
    "muteHttpExceptions":true
  };

  response = UrlFetchApp.fetch(url, options);

  content = response.getContentText(); 
  Logger.log(response); 
  Logger.log(content);
}

Upvotes: 1

Related Questions