Skip to content

Instantly share code, notes, and snippets.

@levelsio
Created October 8, 2023 17:28
Show Gist options
  • Save levelsio/93711253dc71e95aa75a12a8cceec52a to your computer and use it in GitHub Desktop.
Save levelsio/93711253dc71e95aa75a12a8cceec52a to your computer and use it in GitHub Desktop.
This script upgrades the price on active subscriptions on Stripe
<?
// set price
$newPricePlanId='price_1NsRt5Inbsdfsfddsf';
$newPriceMonthly=39;
$i=1;
foreach($users as $user) {
if(!$user['stripe_customer_id']) {
echo "No Stripe customer id, maybe update in db?";
echo "\n";
continue;
}
// <get customer's active subscription>
$subscriptions = $stripe->subscriptions->all([
'customer'=>$user['stripe_customer_id'],
'status'=>'active',
'limit'=>1
]);
// </get customer's active subscription>
if(!$subscriptions['data']) {
echo "No active subscriptions, maybe update in db?";
echo "\n";
continue;
}
$subscription=$subscriptions['data'][0];
$subscriptionItem=$subscriptions['data'][0]['items']['data'][0];
$plan=$subscriptionItem['plan'];
// don't upgrade user to new plan if their next billing cycle is too soon
if($subscription['current_period_end']<strtotime("+30 days")) {
echo "Next billing time is in ".timeAgoLong($subscription['current_period_end']).", so it's too soon, so skip for now";
echo "\n";
continue;
}
echo '#';
echo $i;
echo "\t";
echo $user['email'];
echo "\t";
// <upgrade plan on Stripe>
echo "Updating plan to $39/mo...";
try {
$stripe->subscriptions->update(
$subscription['id'],
[
'items'=>[[
'id'=>$subscriptionItem['id'],
'plan'=>$newPricePlanId,
'quantity'=>1
]],
'proration_behavior'=>'none'
]
);
} catch(\Stripe\Exception\ApiErrorException $e) {
echo "Stripe error: could not upgrade ".$e->getMessage();
echo "\n";
continue;
}
echo "Done!";
echo "\n";
echo 'https://dashboard.stripe.com/customers/'.$user['stripe_customer_id'];
echo "\n";
// </upgrade plan on Stripe>
// <save new plan and price to db>
$query=$usersDb->prepare("UPDATE users SET
mrr=:mrr,
subscription_amount=:subscription_amount
WHERE
stripe_customer_id=:stripe_customer_id
");
$query->bindValue(':mrr',$newPriceMonthly);
$query->bindValue(':subscription_amount',$newPriceMonthly);
$query->execute();
// </save new plan and price to db>
// <email user here>
// </email user here>
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment