Skip to content

Instantly share code, notes, and snippets.

@levelsio
Last active May 7, 2024 18:01
Show Gist options
  • Save levelsio/9f832030058e8173d81744e9ec929669 to your computer and use it in GitHub Desktop.
Save levelsio/9f832030058e8173d81744e9ec929669 to your computer and use it in GitHub Desktop.
<?
// this script receives a Stripe dispute / chargeback and:
//
// - immediately refunds the payment
// - closes the user's account (in my DB, add your own code there)
//
// this is to automate dispute handling (because you never win a dispute on Stripe anyway)
// and by refunding avoiding the chargeback fee
//
// tie this to a webhook inside Stripe's dashboard for the event charge.dispute.created
//
$_DATA = @file_get_contents('php://input');
$_DATA = json_decode($_DATA,true);
if(!empty($_DATA['data']['object']['charge'])) {
$charge_id=$_DATA['data']['object']['charge'];
require_once(__DIR__.'/../vendor/autoload.php'); /* this is my Composer that loads Stripe's PHP library, you can add your own code here to load Stripe PHP */
\Stripe\Stripe::setApiKey(
/* add your live key here */
);
try {
$charge = \Stripe\Charge::retrieve($charge_id);
// <refund charge immediately to avoid chargeback>
try {
$charge = \Stripe\Refund::create(array(
'charge' => $charge_id
));
}
catch(\Stripe\Error\InvalidRequest $e) {
}
catch(\Stripe\Error\Card $e) {
}
// </refund charge immediately to avoid chargeback>
// <disable user>
if(!empty($charge['customer'])) {
// found customer object
// now do a db call to find which user it is
$stripe_customer_id=$charge['customer'];
/* add your own DB logic here to load your user db */
$query=$usersDb->prepare("SELECT * FROM users WHERE stripe_customer_id=:stripe_customer_id");
$query->bindValue(':stripe_customer_id',$stripe_customer_id);
$query->execute();
$userFound=$query->fetchAll(PDO::FETCH_ASSOC);
if(!empty($userFound)) {
$user=$userFound[0];
// add your own logic here to disable user in your db
}
exit;
}
// </disable user>
} catch (Exception $e) {
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment