Stripe and Google Apps Script: Automate Payments, Invoices

Introduction
Integrating Stripe’s powerful payments platform with Google Apps Script opens a world of automation for businesses that rely on Google Workspace tools. Whether you need to charge customers directly from a Google Sheet, generate invoices on the fly, or sync transaction data with Google Drive, the Stripe Payments API can be called from Apps Script with just a few lines of JavaScript. This article walks you through the entire process: from preparing your Stripe account and Apps Script project, to securely authenticating requests, creating charges, handling responses, and setting up automated invoicing and webhooks. By the end, you’ll have a reusable code base that lets you manage payments without leaving the familiar Google environment.

Setting Up Stripe and Google Apps Script Environment

Before writing any code, you must prepare both Stripe and Apps Script:

  • Create a Stripe account and navigate to the Developers → API keys section. Copy the Secret Key (test mode for development, live key for production).
  • Open Google Drive, create a new Google Apps Script project, and give it a meaningful name such as “Stripe Integration”.
  • Enable the UrlFetchApp service (enabled by default) which allows the script to make HTTPS requests to Stripe’s endpoints.
  • Store the secret key safely. The recommended approach is to use the PropertiesService.getScriptProperties() store and set the key via the script editor’s Project SettingsScript properties.

With the environment ready, you can start coding the functions that will communicate with Stripe.

Authenticating Requests with the Secret Key

Stripe expects every API call to include the secret key in the HTTP Authorization header using the Bearer scheme. In Apps Script this is achieved with UrlFetchApp.fetch() and a properly built options object:

function getStripeHeaders() {
  const secret = PropertiesService.getScriptProperties().getProperty('STRIPE_SECRET');
  return {
    'Authorization': 'Bearer ' + secret,
    'Content-Type': 'application/x-www-form-urlencoded'
  };
}

All subsequent calls will merge this header object with any method‑specific options (e.g., method: 'post', payload). Keeping the header logic in a single helper function makes it easy to rotate keys or switch between test and live environments without touching the core business logic.

Creating a Charge and Handling Responses

Charging a customer is the most common operation. The Stripe endpoint for a one‑time charge is https://api.stripe.com/v1/charges. Below is a robust function that accepts the amount (in cents), currency, source token, and an optional description:

function createCharge(amount, currency, source, description) {
  const url = 'https://api.stripe.com/v1/charges';
  const payload = {
    amount: amount,
    currency: currency,
    source: source,
    description: description || ''
  };
  const options = {
    method: 'post',
    headers: getStripeHeaders(),
    payload: payload,
    muteHttpExceptions: true
  };
  const response = UrlFetchApp.fetch(url, options);
  const result = JSON.parse(response.getContentText());

  if (response.getResponseCode() === 200) {
    Logger.log('Charge succeeded: %s', result.id);
    return result;
  } else {
    Logger.error('Stripe error %s: %s', result.error.type, result.error.message);
    throw new Error('Stripe charge failed: ' + result.error.message);
  }
}

The function parses the JSON response, logs successful charges, and throws a detailed error when Stripe returns a failure. This pattern—checking getResponseCode() and handling error objects—should be reused for all API interactions.

Automating Invoicing and Webhooks in Apps Script

Beyond one‑off charges, many businesses need recurring invoices or real‑time notifications. Apps Script can generate invoices by calling /v1/invoices and can also act as a lightweight webhook receiver using the built‑in doPost(e) handler.

  • Invoice creation: Build a function similar to createCharge but targeting the invoice endpoint, attaching line items, and setting collection_method to send_invoice. After creation, call /v1/invoices/{id}/send to email the customer automatically.
  • Webhook listener: Deploy the script as a web app (accessible to anyone, even anonymously). The doPost(e) function receives the raw JSON payload from Stripe, verifies the signature using the stripe-signature header, and then processes events such as invoice.payment_succeeded or charge.refunded. Example skeleton:
    function doPost(e) {
      const payload = e.postData.contents;
      const sigHeader = e.postData.headers['stripe-signature'];
      // Verify signature (requires crypto library or external service)
      const event = JSON.parse(payload);
      switch (event.type) {
        case 'invoice.payment_succeeded':
          // Update Google Sheet, send thank‑you email, etc.
          break;
        // handle other event types as needed
      }
      return ContentService.createTextOutput('OK');
    }

By combining invoice automation with webhook handling, you can keep your Google Workspace data in sync with Stripe without manual intervention.

Best Practices and Troubleshooting

To ensure a stable integration, follow these guidelines:

  • Use test mode for development. Always validate logic with Stripe’s test cards before switching to live keys.
  • Secure the secret key. Never hard‑code it; use script properties or Google Secret Manager.
  • Implement exponential back‑off. Network hiccups can cause temporary failures; retry failed requests after a short delay.
  • Log critical events. Store charge IDs, invoice numbers, and webhook timestamps in a dedicated Sheet for audit trails.
  • Monitor quota limits. Apps Script has daily URLFetch limits; batch requests or use time‑driven triggers to stay within bounds.

If you encounter “429 Too Many Requests” errors, reduce the request rate or switch to Stripe’s Connect platform for higher limits. For signature verification failures, double‑check the webhook endpoint secret and ensure the request body is not altered by Apps Script’s automatic parsing.

Conclusion
Integrating Stripe’s Payments API with Google Apps Script empowers you to manage transactions, generate invoices, and react to real‑time events—all from within the Google Workspace ecosystem. By setting up a secure environment, authenticating each request with a helper function, and handling charges and invoices with reusable code, you create a robust foundation that scales from simple one‑off payments to complex recurring billing workflows. Adding a webhook listener further automates bookkeeping and customer communication, while best‑practice recommendations keep the integration reliable and secure. With these tools at your disposal, you can streamline financial operations, reduce manual effort, and focus on growing your business rather than wrestling with disparate systems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Digital Malayali