Integrating Stripe PHP library into a custom WordPress Plugin

I am trying to create a simple ‘add monthly Subscriptions(Monthly payments) button’ custom plugin for a clients WordPress website. My current issue is how am I to include Stripe’s PHP library in the plugin? I have Stripe operational running it through Composer (autoload.php) locally. But adding it to WordPress….

I have added the basic code from Stripe’s website below:
https://stripe.com/docs/recipes/subscription-signup

 <form action="/create_subscription.php" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_mlHAlLZMWfb2URJZIvb6Qntd"
    data-image="/images/marketplace.png"
    data-name="Emma's Farm CSA"
    data-description="Subscription for 1 weekly box"
    data-amount="2000"
    data-label="Sign Me Up!">
  </script>
</form>

This is the PHP.

<?php // Create a customer using a Stripe token

// If you're using Composer, use Composer's autoload:
require_once('vendor/autoload.php');

// Be sure to replace this with your actual test API key
// (switch to the live key later)
\Stripe\Stripe::setApiKey("sk_test_000000000000");

try
{
  $customer = \Stripe\Customer::create(array(
    'email' => $_POST['stripeEmail'],
    'source'  => $_POST['stripeToken'],
    'plan' => 'weekly_box'
  ));

  header('Location: thankyou.html');
  exit;
}
catch(Exception $e)
{
  header('Location:oops.html');
  error_log("unable to sign up customer:" . $_POST['stripeEmail'].
    ", error:" . $e->getMessage());
}

Any help would be appreciated!

1 Answer
1

Check out this article. It’s kind of old, but still quite relevant – I used it to build my own Stripe integration plugin for WordPress.

Note that including the line:

require_once('vendor/autoload.php');

should load the Stripe libraries for you. Depending on how you have your plugin folders set up, the plugin might not be finding the autoload.php file. It’s best to set a base directory in your plugin’s primary php file as such:

if ( ! defined( 'PLUGINNAME_BASE_DIR' )) 
    define( 'PLUGINNAME_BASE_DIR', dirname( __FILE__ ) );

Then, your require statement would look like:

require_once( PLUGINNAME_BASE_DIR . '/vendor/autoload.php' );

Even better, put the Stripe library in a /lib folder in your plugin, so your include would be:

require_once( PLUGINNAME_BASE_DIR . '/lib/stripe-php/vendor/autoload.php' );

There is also an init.php file in the library that does the same thing and is what I used since I didn’t use Composer to pull it in. You can use this by downloading the source for the stripe-php library and putting the raw source in your plugin directory inside a /lib directory.

require_once( PLUGINNAME_BASE_DIR . '/lib/stripe-php/init.php' );

Leave a Comment