2

Trying to use this example code to create Stripe checkout and charges inside Google Apps Script.

HTML.html

<!DOCTYPE html>
<!-- modification of https://stripe.com/docs/checkout#integration-custom -->
<button id="customButton">Purchase</button>

<script src="https://checkout.stripe.com/checkout.js"></script>  
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>
var handler = StripeCheckout.configure(
{
  key: 'pk_test_UUbDY16wDCECOujIs0vQ2vTi',
  image: 'https://i.imgur.com/M0ku9HH.png',
  token: function(token) 
  {
    // Use the token to create the charge with a server-side script.
    // You can access the token ID with `token.id`
    google.script.run.withSuccessHandler(chargeSuccess)
    google.script.run.withFailureHandler(chargeFailure)
    google.script.run.processCharge(token);
  }
}
);

$('#customButton').on('click', function(e) 
{
  // Open Checkout with further options
  handler.open(
  {
    name: 'ASD Anastasiya Ballet S.',
    description: 'Pagamento online'
  });
  e.preventDefault();
});
function chargeSuccess(result) {
  // handle response code client side 
}
function chargeFailure(error) {
  // client error handling
}
</script>

GS.gs
// IFRAME mode required
function doGet() {
return HtmlService.createHtmlOutputFromFile('HTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

/**
 * Read Stripe token passed from google.script.run instead of
 * using a form POST request - which can't happen in HtmlService.
 *
 * @param {Object} token from checkout.js
 * @return {number} HTTP Response code 
 */
function processCharge(token) { 


var tokenId = token.id;
var stripeEmail =  token.email;

// Create a Customer ( optional )
/*
var path = "/customers";
var customer = Stripe_PostRequest(path, [], [], {
  "description": "test customer", 
  "source": tokenId,
  "email": stripeEmail
});

var custId = JSON.parse( customer.getContentText() ).id;
*/

// Create a Charge
path = "/charges";
var charge = Stripe_PostRequest(path, [], [], {
   "currency": "usd", 
   "amount": "500",
   //"customer": custId
});

return charge.getResponseCode();
}

/**
 * Generic function for making a POST request to the Stripe API.
 * Provided by Stripe support
 *
 * @param {string} path
 * @param {Object} parameters 
 * @return {HTTPResponse} 
 */
var Stripe_PostRequest = function(path, fields, expandableFields, parameters) {
  // Expand related fields when accessing sub-properties
  // (e.g. `customer.email` should expand the customer
  // object when retrieving a charge).
  if (expandableFields !== undefined) {
    parameters["expand[]"] = [];
    fields.forEach(function(field) {
      field = field.split(".")[0];
      if (expandableFields.indexOf(field) !== -1) {
        parameters["expand[]"].push("data." + field);
      }
    });
  }

  var scriptProperties = PropertiesService.getScriptProperties();
  var secret = scriptProperties.getProperty('testSecret');

  var options = {
    "method" : "post",
    "headers": {
      "Authorization": "Bearer " + secret,
      "User-Agent": "Stripe Example/0.1"
    }
  };
  var url = "https://api.stripe.com/v1" + path + serializeQueryString(parameters);
  return UrlFetchApp.fetch(url, options); 
}

/**
 * Serialize a dictionary to a query string for GET requests
 */
var serializeQueryString = function(parameters) {
  var str = [];
  for (var key in parameters) {
    var value = parameters[key];
    if (parameters.hasOwnProperty(key) && value) {
      if (value.map) {
        str.push(value.map(function(array_value) {
          return key + "=" + encodeURIComponent(array_value);
        }).join("&"));
      } else {
        str.push(key + "=" + encodeURIComponent(value));
      }
    }
  }
  return '?' + str.join("&");
}

The form work fine but no charge is created since seems no token was created. Being not at all a JS expert I'm not sure if the function

token: function(token)

that calls

google.script.run.processCharge(token);

is executed correctly.

2
  • First of all, your function call looks not like in working example: google.script.run.withSuccessHandler(chargeSuccess) .withFailureHandler(chargeFailure) .processCharge(token); Commented Nov 26, 2017 at 21:31
  • Yes I changed it supposing was not clear. This is not the problem, appear I'm not able to send the correct key. Not sure if the Google Script POST create function is working correctly. Any way using Google Script to create the standard stripe.charges.create call. Commented Nov 27, 2017 at 0:40

1 Answer 1

3

Your code is failing as you've commented out the custId - this has to be provided. There's no harm in leaving this in, it'll simply create a test customer. Otherwise create a customer in the Stripe control panel and copy the ID into custId.

You can always look in "View > Execution transcript" to get clues as to why the script is failing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.