Last active
May 7, 2024 18:01
-
-
Save levelsio/9f832030058e8173d81744e9ec929669 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// 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