Home > Tools & Templates > Stripe PHP Webhook Code

Stripe PHP Webhook Code: payment_intent.succeeded Event

Structured Webhook Implementation for Stripe Post-Payment Workflows

This code serves as a foundational framework for Stripe payment event integration. It offers a professional starting point for developers tasked with building Stripe PHP processing scripts. Utilizing the Stripe object-oriented API to map payment events to specific class-based data items can be complex; this script provides a clear architectural baseline to facilitate that integration.

Integrate Stripe into your e-commerce workflow with our professional PHP Webhook Code. Designed specifically for payment_intent.succeeded events, this code snippet reduces development time for research, implementation, and testing. This script processes data from Stripe success events, logs transaction details via the Stripe PHP API, and supports the automated delivery of digital products or the triggering of custom backend workflows.

Your purchase is securely processed by PayPal.
Delivered in minutes: How it works.

Features of the Stripe PHP Webhook

  • Automated Workflow: Reduce manual intervention by automating post-payment processes, allowing you to focus on managing your business.
  • Data Retrieval: Utilize the Stripe PHP API to retrieve and store transaction data for accurate record-keeping and database synchronization.
  • Execution Logging: Monitor webhook execution and purchase data to simplify troubleshooting and verify system health.
  • Technical Support: We offer USA-based technical support via phone and email to assist with your implementation.
  • Server-Side Solution: Host the functionality on your own server or shared hosting plan to maintain data control and avoid third-party subscription fees.

Implementation details:

  • Dependencies: Integrate the Stripe PHP library via Composer for streamlined dependency management.
  • Secure Key Handling: Manage your Stripe Secret API Key using the PHP dotenv library to load keys from an external .env file.
  • Structured Integration: Our provided code snippet uses Composer's autoload to support clean binding of the Stripe PHP and phpdotenv libraries.
  • Customizable Workflows: Tailor the post-payment process by utilizing Stripe Metadata. The included sendMail() function demonstrates how to automate email attachments based on transaction data.

Benefits of Our Stripe PHP Webhook

  • Automate the delivery of products via email attachments.
  • Reduce expenses by eliminating monthly subscription fees for third-party webhook services.
  • Get Tech Support that is USA-based ( Call or Email Us!)
  • Lookup Product Data via the Stripe PHP API:
    • Retrieves customer_details from the current stripe session data object such as:
      • customer email
      • customer name
    • Retrieves the line_items collection from the current stripe session data object and processes purchase data such as:
      • id (line_item)
      • quantity
      • description
      • price object
        • id (product)
        • unit_amount
  • Log Webhook Execution Progress and Purchase Data:
    Sample Stripe Webhook Log File Name: log_26-Sep-2023.log

    26-Sep-2023 Stripe Log
    02:22:20pm - Starting execution.
    02:22:20pm - Response OK
    02:22:20pm - processing: payment_intent.succeeded event.
    02:22:25pm - Email: [email protected]
    02:22:25pm - Name: john doe
    02:22:25pm - Line Item Id: li_1Nuc8fA2CUhNBxyOeqZMYDSd
    02:22:25pm - Product Id: prod_N8dEoQ10mY8Bkk
    02:22:25pm - Qty: 1
    02:22:25pm - Desc: Maintenance Checklists in Excel
    02:22:25pm - Price: 149
    02:22:26pm - Product delivered automatically via Email or Link. Metadata product_email_filename: maint-checklists.zip
    02:22:26pm - Product delivered via Link
    02:22:26pm - Email accepted by server.
    02:22:26pm - Webhook completed OK

Implementation Guidelines for Our Stripe PHP Webhook

  1. The Stripe PHP library is required to provide access to the Stripe API. Installation of the Stripe PHP library is easy via Composer. For example, run $ composer require stripe/stripe-php to install on a Linux web server.
  2. Consider how you will store and access your Stripe Secret API Key. In our example, we make use of the PHP dotenv library to load the Stripe Secret API Key as an environment variable from a .env file that resides outside of our web server's public folder. Installation of PHP dotenv is easy via Composer. For example, run $ composer require vlucas/phpdotenv to install on a Linux web server.
    Note: Alternately, hard-coding the secret key directly in the PHP Webhook would be ok for the Test Mode Secret Key of the Stripe Secret API Key but significantly risky for the Live Mode Secret Key.
  3. For binding the Stripe PHP and phpdotenv libraries within our PHP Webhook, we use Composer's autoload: require_once 'vendor/autoload.php';
    Note: Alternately, the Stripe PHP library may be loaded without Composer but you must manually install the library and verify that your web server has the required Stripe PHP library dependencies ( curl, json, and mbstring). phpinfo() may be used to check the status of extensions.
  4. Add a Metadata key, value pair via the Stripe Dashboard for each product you would like delivered via email. The key is "product_email_filename" and the value is the filename of the product you would like delivered via email upon checkout completion. In the case of this product it is "StripePHPWebhookCode.pdf". This Metadata will be used by the Stripe PHP Webhook's sendMail() function for attaching the product's file.
  5. Configure the Stripe PHP Webhook for your implementation.
    1. Set the Sender Information within the following code block of the sendMail() function:
      // Sender Information
      $from = ' [email protected] ';
      $fromName = ' Sender Name or Company Name ';
    2. Set the Webhook Log File Location and File Name Format within the logWebhookStatus() function. For security, we place the log file outside of the web server's public folder. See the following code block:
      // Webhook log file location and naming convention
      $log_file_dir = $_SERVER["DOCUMENT_ROOT"] . " /../stripe-logs ";
      $log_file_name = $log_file_dir . " /log_ " . date("d-M-Y") . ".log";
    3. Verify the loading of the required dependencies: Stripe PHP Library and PHP dotenv. For security, we installed the libraries outside of the web server's public folder. See the following code block:
      // Load the dependencies installed via Composer (Stripe PHP Library and PHP dotenv)
      require " ../stripe-lib/vendor/autoload.php ";
    4. Store your Stripe API Secret Key in a .env file outside the web server's public folder. In this example, we store the key in custom.env located in a folder named secret within the parent folder of your public folder. The custom.env file should initially contain the following entry:
      SECRET_KEY=" sk_test_...... "
      Note: This key may be later set to the "sk_live_......" Live Secret Key after completion of testing.
    5. Verify the path is correct for loading the Stripe API Secret Key within the following code block:
      // Load the Stripe API Secret Key into the environment variable SECRET_KEY via PHP dotenv from custom.env that is outside the web server's public folder
      $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . " /../secret ", " custom.env ");
      $dotenv->load();
    6. Initialize the Stripe PHP Client with the API Secret Key stored as an environment variable. See the following code block:
      // Initialize the Stripe PHP Client with the API Secret Key stored as an environment variable
      $stripe = new \Stripe\StripeClient($_SERVER['SECRET_KEY']);
    7. Set the Stripe Webhook Signing Secret Key within the following code block:
      // Signing Secret Key for the Webhook
      $endpoint_secret = " whsec_...... ";
    8. Specify the path for products emailable as attachments. For security, we are using a folder outside of our web server's public folder. See the following code block:
      // Specify path to emailable products folder
      $path_emailable_products = $_SERVER["DOCUMENT_ROOT"] . " /../products-emailable/ ";
    9. Set the email signature for product deliveries within the following code block:
      // Construct the email signature
      $email_html_signature = ' <p>Best regards,<br />John Doe<br />Owner,<br />yourdomain.com<br />555-555-5555</p> ' ;
    10. Create your Stripe Webhook Endpoint for testing.
      1. Sign in to the Stripe Dashboard.
      2. Click Developers button.
      3. Switch the Test mode setting to the On Position (lit in orange).
      4. Click the Webhooks tab under the Developers pageframe.
      5. Click the Add endpoint button.
      6. Helpful sample code is displayed in the right-hand pane.
        Note, the Listen to Stripe events page also displays information and settings regarding testing on a local server which will not be covered in this guide.
      7. Enter the Endpoint URL which should point to the test version of your PHP Webhook hosted on your server.
        Example: https://www.yourdomcain.com/stripe-webhook-test.php
      8. Click the Select events button.
      9. Choose Payment Intent events.
      10. Mark the payment_intent.succeeded event.
      11. Click the Add events button.
      12. You should now have successfully created a Test Webhook Endpoint for the payment_intent.succeeded event.
    11. Please see Testing within the Stripe Docs for helpful information about Stripe Test mode and how to use test cards for the simulation of Stripe payments.
    12. Note: Within the Stripe Dashboard, you may click on a Hosted endpoint to view event history, status, and data. Notably, a "Resend" button is available which is useful for testing and verifying logic corrections.

 

Thank you for viewing our product. Please Contact Us with product questions or feedback.