Stripe payment using Google Apps Script

2019-08-19 17:00发布

问题:

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

HTML.html file

<!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>

Here the GS.gs file

// 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.

回答1:

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.