Anyone set up subscription services using Stripe?

Hi,
Has anyone set up a subscription service with MODx using stripe for payments?

i have a site that relies on Stripe subscription, etc. Do you any questions?

Thanks for responding. Could you post or pm me a link please?

I also need to do this with a subscription service, and save their credit card for automatic payments, etc. Plus let them update their info, the whole 9 yards.

I haven’t dug into the Stripe API yet to begin setting it up. Couldn’t find a good library to begin with.

Stripe’s API is very well documented. Their PHP library is publicly available on Github.

Assuming you’re subscribing your users at signup time, using the Login extra, you could start things off with a simple preHook that I’d call subscribeCustomer with the following code:

// load stripe's SDK
require_once('path/to/stripe-php/init.php'); // update path accordingly

\Stripe\Stripe::setApiKey('your_stripe_api_key');

// get form data
$email = $hook->getValue('email');
$plan  = $hook->getValue('plan');
$token = $hook->getValue('stripeToken');

$output = '';
$error  = '';

// create customer on stripe
try {
    $customer = \Stripe\Customer::create(array(
        'email' => $email,
        'source' => $token        
    ));   
    $output = true;   
} catch (Exception $e) {      
    // something went wrong, display and log error
    $error = "Unable to create the customer ({$email}) on Stripe. " . $e->getMessage();
    $hook->addError('stripe-customer', $error);
    $modx->log(modX::LOG_LEVEL_ERROR, $error);
    $output = false;    
}

// subscribe the customer to the plan
try {
  $subscription = \Stripe\Subscription::create([
    'customer' => $customer->id,
    'items' => [['plan' => $plan]]    
  ]);
  
  // optional, but recommended: 
  // save stripe's customer id (and susbscription id) in extended fields or in custom db table
  // for later reference when interacting with stripe's API 
  $hook->setValue('stripeid', $customer->id);
  $hook->setValue('stripesubscription', $subscription->id);
  $output = true;
} catch (Exception $e) {
    $error = 'unable to subscribe the customer to the plan on Stripe. ' . $e->getMessage();
    $hook->addError($error);  
    $modx->log(modX::LOG_LEVEL_ERROR, $error);
    $output = false;
}

return $output;

This hook handles the subscription form data once submitted. It assumes that a plan already exists on Stripe and that the user will have the option of selecting it at signup time. Of course, it could also be hard-set in the code if only one applies.

Hope this gets you started faster.

2 Likes

Same goes with me…I m planning to do it since year…Unfortunately due to lack of good library resources it is still on hold…Will find soon though,just a hope.