Stripe Webhooks Integration: 4 Easy Steps, Key Events, Triggers, and Best Practices

By: Published: November 2, 2021

Stripe Webhook FI

Stripe provides its users with Application Programming Interfaces (APIs) for Mobile Apps and E-Commerce Websites, as well as payment processing tools. Stripe’s payment solutions are utilized by software platforms, marketplaces, subscription businesses, in-store shops, and online retailers. When an event/thing occurs, Webhooks are sent automated messages from Apps. They send a message or payload to a specific URL, which is the phone number or location of the App. Webhooks are relatively always faster and take less effort on your part than polling.

In this in-depth article, you will learn about Stripe Webhooks Integration available for fulfilling your E-Commerce tasks efficiently. You will gain a decent understanding of each and every step required to complete this integration.

Table of Contents

What are Webhooks?

Stripe Webhook - Webhook logo
Image Source

Polling and Webhooks are two distinct methods for your Apps to communicate and share information with one another. Polling is similar to knocking on a friend’s door and asking if they have any sugar (aka information), except you have to ask each time you want it. Webhooks are like having a bag of sugar delivered to your door every time they buy some. You don’t even have to ask; they just give it to you when it’s convenient.

Webhooks allow Apps to deliver Automated Messages when anything happens. They deliver a message or payload to a certain URL, which is the App’s phone number or location. Webhooks are almost always faster than polling and require less effort on your part.

What is Stripe?

Stripe Webhook - STripe logo
Image Source

Stripe is an Online Payment Processing Solution that accepts debit cards, credit cards, and other local payment methods preferred by the consumer. Stripe was founded in 2009 with the goal of making the credit card payment process easier for both companies and customers. Stripe has expanded its horizons over time and now supports all major debit and credit cards, as well as Apple Pay and Google Pay for quick checkouts. Stripe has been used by a variety of E-Commerce companies, subscription businesses, software platforms, and marketplaces with great success.

Stripe allows you to develop and customize a mobile-friendly checkout experience for your Customers. Charges, Fees, Refunds, and Transfers are all updated in real-time for both the Vendor and the Customer. The user-friendly Stripe Dashboard allows you to keep track of all transactions made using various payment methods all over the world.

Stripe secures the user’s sensitive data throughout a transaction by leveraging its PCI-DSS Compliant Payment Processor. You can acquire transparent risk assessments and real-time fraud insights with the Stripe Radar Machine Learning technology. Preventing fraudulent transactions requires constant monitoring for any unusual activity. Stripe offers an extra layer of security for high-risk transactions by using 3D Secure Authentication, which requires the user to go through an additional verification process before making a payment.

Key Features of Stripe

Stripe’s enormous popularity can be attributed to the following features:

  • Cost Efficient: Stripe is cost-effective because there are no monthly or annual costs for registering an account and using the payment platform. It also has no hidden fees for installation, account termination, or other comparable services. The only costs associated with using this platform are transaction fees and a charge of $15 for chargebacks.
  • Customizable: Developers choose this platform because it is simple to use and customize. Stripe also allows developers to effectively manage the UI of the entire payment process.
  • Secure: To protect your company transactions, Stripe uses a Machine-Learning-Based Anti-Fraud System called Radar. This technology uses data from millions of businesses around the world to assist distinguish between fraudulent and legitimate purchases.
Simplify ETL with Hevo’s No-code Data Pipeline

A fully managed No-code Data Pipeline platform like Hevo Data helps you integrate and load data from 100+ Different Sources like Stripe and Webhooks (40+ Free Data Sources) to a Data Warehouse or Destination of your choice in real-time in an effortless manner. Hevo with its minimal learning curve can be set up in just a few minutes allowing the users to load data without having to compromise performance.

Get Started with Hevo for Free

It helps transfer data from Stripe to a destination of your choice for free. Its strong integration with umpteenth sources allows users to bring in data of different kinds in a smooth fashion without having to code a single line. 

Check out some of the cool features of Hevo:

  • Completely Automated: The Hevo platform can be set up in just a few minutes and requires minimal maintenance.
  • Connectors: Hevo supports 100+ Integrations to SaaS platforms like Shopify, files, Databases, analytics, and BI tools. It supports various destinations including Google BigQuery, Amazon Redshift, Snowflake Data Warehouses; Amazon S3 Data Lakes; and MySQL, SQL Server, TokuDB, DynamoDB, PostgreSQL Databases to name a few.  
  • Real-Time Data Transfer: Hevo provides real-time data migration, so you can have analysis-ready data always.
  • 100% Complete & Accurate Data Transfer: Hevo’s robust infrastructure ensures reliable data transfer with zero data loss.
  • Scalable Infrastructure: Hevo has in-built integrations for 100+ sources (including 40+ free sources) such as Shopify, that can help you scale your data infrastructure as required.
  • 24/7 Live Support: The Hevo Team is available round the clock to extend exceptional support to you through chat, email, and support calls.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Live Monitoring: Hevo allows you to monitor the data flow so you can check where your data is at a particular point in time.
Sign up here for a 14-Day Free Trial!

Use Cases for Stripe Webhooks

Stripe Webhook - Integration
Image Source

Stripe Webhook event notifications can be used to notify your App:

  • When a Subscription Payment is successful (customer.subscription.created), allow your App to change the Customer’s Database membership record.
  • When a customer has paid their invoice (invoice.payment_succeeded), allow your App to update the Customer’s Records in your accounting system as paid.

Steps to Set up a Stripe Webhook Endpoint

It’s no different than building any other page on your website when it comes to adding a Stripe Webhook Endpoint. It’s a URL for an HTTP or HTTPS endpoint on your server. It can also be HTTP if you’re still constructing your endpoint on your local workstation. But, it must be HTTPS once it is publicly accessible. You can use a single endpoint to handle many event types at the same time, or you can create distinct endpoints for specific events. Below are the steps needed to be carried out to set up Stripe Webhook Endpoints:

Step 1: Analyze and Identify the Events to Monitor

Determine the kind of API Events and Event Objects that your Stripe Webhook Endpoint must parse.

Step 2: Build a Webhook Endpoint

Set up an HTTP endpoint on your local system that can receive POST requests from unauthenticated Stripe Webhooks. This Flask route, for example, is a map to a Python Stripe Webhook function:

@app.route('/stripe_webhooks', methods=['POST'])
def webhook():
    stripe_payload = request.json

The /stripe_webhooks route is configured to accept only POST requests and data in the form of a JSON payload in this example.

Step 3: Handling Stripe Requests

For the sort of event notifications you want to receive, your Endpoint must be set up to read event objects. Stripe uses a POST request with a JSON payload to transmit events to your Webhook destination.

A) Checking Event Objects

Each event is organized as an event object, with a type, id, and associated Stripe resource nested beneath data. Each event’s payload must be parsed by your Endpoint, which must check the event type.

{
  "id": "evt_2Zj5zzFU3a9abcZ1aYYYaaZ1",
  "object": "event",
  "api_version": "2020-08-27",
  "created": 1633887337,
  "data": {
    "object": {...}
}

B) Returning a 2xx Response

Prior to any complex logic that could cause a timeout, your Endpoint must promptly provide a successful Status Code (2xx). For example, before updating a customer’s invoice as paid in your accounting system, you must return a 200 Response.

@app.route('/stripe_webhooks', methods=['POST'])
def webhook():
    event = None
    payload = request.data
    sig_header = request.headers['STRIPE_SIGNATURE']

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except ValueError as e:
        # Invalid payload
        raise e
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        raise e

    # Handle the event
    print('Unhandled event type {}'.format(event['type']))

    return jsonify(success=True)

The Python code in the preceding example checks for the event type and gives a 200 response.

C) Built-in Retries

For 3xx, 4xx, or 5xx Response Status Codes, Stripe Webhooks include built-in retry methods. If Stripe does not get a 2xx Response Status Code for an event within a reasonable amount of time, it labels the event as failed and stops sending it to your Endpoint. After a few days, it’ll send you an email about the misconfigured Endpoint, and if you don’t respond, it’ll shut it automatically.

Step 4: Check Client Signatures

Use Webhook signatures to ensure that a Webhook request was generated by Stripe and not by a server impersonating Stripe.

Test Stripe Webhooks using CLI

To test your Stripe Webhook Endpoint locally, use the Stripe CLI. Without any further settings, you can start listening to and even triggering events with the Stripe CLI. This allows you to quickly test a Stripe Webhook Integration without exposing your Stripe Webhook Endpoint (URL) to the public. When you use the Stripe CLI to trigger events, you’ll get event objects containing Real Data. Real Data can be used to verify that your Stripe Webhook Endpoint executes any sophisticated endpoint logic after receiving a 2xx Response. Below are the steps needed to be carried out to test Stripe Webhook using CLI:

Step 1: Install Stripe CLI

A) Installing Stripe CLI in macOS

To install the Stripe CLI on macOS, follow these steps:

  • Download the latest mac-os tar.gz file from https://github.com/stripe/stripe-cli/releases/latest.
  • Unzip the file as follows: tar -xvf stripe_X.X.X_mac-os_x86_64.tar.gz

Install the binary in a location where it can be run globally (for example, /usr/local/bin).

B) Installing Stripe CLI in Linux

To install the Stripe CLI on Linux without a package manager, follow these steps:

  • Download the latest linux tar.gz file from https://github.com/stripe/stripe-cli/releases/latest.
  • Unzip the file as follows: tar -xvf stripe_X.X.X_linux_x86_64.tar.gz
  • ./stripe should now be on your execution path.

C) Installing Stripe CLI in Windows

To install the Stripe CLI on Windows, follow these steps:

  • Download the latest windows tar.gz file from https://github.com/stripe/stripe-cli/releases/latest.
  • Unzip the file as follows: stripe_X.X.X_windows_x86_64.zip
  • Run the .exe file that has been unzipped.

Step 2: Integrate Stripe Account

After installing the Stripe CLI, run Stripe login in the terminal to connect it with your Stripe account. To grant the Stripe CLI access to your account, you must first log in to the Stripe Dashboard. You must enter the below command in your command prompt:

stripe login
Your pairing code is: humour-nifty-finer-magic
Press Enter to open up the browser (^C to quit)

Pairing creates two secret API keys, one for Test Mode and the other for Live Mode, both of which are good for 90 days.

Step 3: Push Events to the Server

You can use the Stripe CLI to listen for events after you’ve linked your Stripe account. However, you’ll want to transmit received events to your server to test your Endpoint. When using Stripe Listen, add the —forward-to parameter to the command:

stripe listen --forward-to localhost:5000/hooks
Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit)

Note: Make sure to change localhost:5000/hooks with your Stripe Webhook Endpoint’s address and path!

Step 4: Create an Event Trigger

A trigger command in the Stripe CLI can create specific event kinds for you. Create a payment intent in a new terminal payment_intent.created event:

stripe trigger payment_intent.created

The event, as well as the response from your server, should be visible in the terminal where you ran the Stripe Listen to Command:

stripe listen --forward-to localhost:5000/hooks
Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit)
YYYY-MM-DD HH:MM:SS -->  payment_intent.created [{{WEBHOOK_EVENT_ID}}]
YYYY-MM-DD HH:MM:SS  <--  [200] POST http://localhost:5000/hooks [{{WEBHOOK_EVENT_ID}}]

Best Practices for using Stripe Webhooks

Stripe Webhooks are a great way to keep track of transaction status and perform actions within your Stripe account. Examine these best practices to verify that your Webhooks are safe and work well with your integration.

  • API Version: Test Stripe Webhook Endpoints can be set for either your default API version or the most recent API version. The events sent to the Webhook URL are formatted according to the Endpoint’s version. Endpoints with a certain API version can also be created programmatically.
  • Event Types: Only the types of events required by your integration should be sent to your Stripe Webhook Endpoints. Listening for more events (or all events) will overburden your server and is not recommended. The events that a Stripe Webhook Endpoint will receive can be changed via the Dashboard or via the API.
  • Event Handling: When Webhook events aren’t recognized, learn how to view delivery attempts, event logs, and the retry mechanism.
  • Security: It’s vital to keep your endpoints safe in order to protect your customers’ data. Stripe provides a number of secure ways for you to verify that events are coming from Stripe.

Deploy your Stripe Webhooks

Enable your Stripe Webhooks Integration in production after you’ve tested your Stripe Webhook Endpoint, go live by registering it on the Stripe Dashboard.

Endpoint URL Format

To make your Stripe Webhook Endpoint live, give it a publicly available HTTPS URL and choose the kind of events you want to use. The following is the URL format for registering a Stripe Webhook Endpoint:

https://<your-website>/<your-webhook-endpoint>

For example, if your domain is https://mycompanysite.com and the route to your Webhook Endpoint is @app.route(‘/stripe_webhooks’, methods=[‘POST’]), specify https://mycompanysite.com/stripe_webhooks as the Endpoint URL.

Register your Stripe Webhook Endpoint 

In your Dashboard’s Webhooks settings page, you can provide the publicly accessible HTTPS URL for your Stripe Webhook Endpoint, or you can use Webhook Endpoints programmatically.

Step A: Adding Endpoints in the Dashboard

Stripe has two sorts of endpoints: Account and Connect. Unless you’ve already developed a Connect application, construct an Endpoint for Account.

Click on Add Endpoint in the Webhooks settings section of the Dashboard to see a form for adding a new Endpoint for receiving events. Any URL can be used as the event’s destination. The API documentation has a complete list of event kinds.

Step B: Adding Endpoints using the API

Stripe Webhook Endpoints can also be created programmatically. You can input any URL as the event destination and which event kinds to subscribe to, just like you can on the Dashboard’s form. Use the Connect Parameter to receive events from connected accounts.

The example below establishes an endpoint that alerts you when charges are successful or unsuccessful.

# Set your secret key. Remember to switch to your live secret key in production.
# See your keys here: https://dashboard.stripe.com/apikeys
stripe.api_key = 'sk_test_tR3PYbcVNZZ796tH88S4VQ2u'

endpoint = stripe.WebhookEndpoint.create(
  url='https://example.com/my/webhook/endpoint',
  enabled_events=[
    'charge.failed',
    'charge.succeeded',
  ],
)

Manage Stripe Webhook Endpoint 

In the Webhooks settings tab of the Dashboard, you can modify or delete existing Stripe Webhook Endpoints. You can also disable a Webhook Endpoint for a limited time. Stripe does not retry any produced notifications when the Endpoint is disabled. Alternatively, you can programmatically manage Stripe Webhook Endpoints.

Conclusion

This article teaches you about Stripe Webhooks Integration. It provides in-depth knowledge about the concepts behind every step to help you understand and implement them efficiently. Building a Stripe Webhook connection manually, using API calls can be challenging especially for a beginner & this is where Hevo saves the day.

Visit our Website to Explore Hevo

Hevo Data provides its users with a simpler platform for integrating data from 100+ sources such as Stripe and Webhooks for Analysis. It is a No-code Data Pipeline that can help you combine data from multiple sources. You can use it to transfer data from multiple data sources into your Data Warehouses, Database, or a destination of your choice. It provides you with a consistent and reliable solution to managing data in real-time, ensuring that you always have Analysis-ready data in your desired destination. Hevo supports a Native Webhooks connector that allows users to load data from non-native custom sources without having to write any code.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at our unbeatable pricing that will help you choose the right plan for your business needs!

Share your experience of learning about Stripe Webhooks Integration! Let us know in the comments section below!

mm
Former Research Analyst, Hevo Data

Harsh comes with experience in performing research analysis who has a passion for data, software architecture, and writing technical content. He has written more than 100 articles on data integration and infrastructure.

No-code Data Pipeline for Stripe & Webhooks