Skip to content

Instantly share code, notes, and snippets.

@adamjstevenson
Last active October 4, 2015 19:39
Show Gist options
  • Save adamjstevenson/c9a971b3758c46adbac4 to your computer and use it in GitHub Desktop.
Save adamjstevenson/c9a971b3758c46adbac4 to your computer and use it in GitHub Desktop.
Notify subscription customers of failed payments
<?php
// Sends an email to customers if their payment fails
// 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
\Stripe\Stripe::setApiKey("sk_test_YourAPIKey");
// Retrieve the request's body and parse it as JSON
$input = @file_get_contents("php://input");
$event_json = json_decode($input);
// Check against Stripe to confirm that the ID is valid
$event = \Stripe\Event::retrieve($event_json->id);
if (isset($event) && $event->type == "invoice.payment_failed") {
// If the email address is stored with the customer object, retrieve the customer object
$customer = \Stripe\Customer::retrieve($event->data->object->customer);
$email = $customer->email;
// Sending your customers their total due in pennies is kind of weird, so we'll convert to dollars.
$amount = sprintf('$%0.2f', $event->data->object->amount_due / 100.0);
// Require Mailgun stuff if you're using Mailgun to send emails
use Mailgun\Mailgun;
// Be sure to replace with your Mailgun key and domain
$mgClient = new Mailgun('key-yourKeyGoesHere');
$domain = "yourDomainGoesHere";
// Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
// Be sure to replace the from address with the actual email address you're sending from
'from' => 'YourApp Billing <[email protected]>',
'to' => $email,
'subject' => 'Your most recent invoice payment failed',
'text' => '
Hi there,
Unfortunately your most recent invoice payment for ' . $amount . ' was declined. This could be due to a change in your card number or your card expiring, cancelation of your credit card, or the bank not recognizing the payment and taking action to prevent it.
Please update your payment information as soon as possible by logging in here:
https://yoursite.com/login'
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment