Created
September 22, 2016 19:01
-
-
Save adamjstevenson/0aee84d54865bff5ad9954afcecfe01d to your computer and use it in GitHub Desktop.
Charge dynamic application fees based on card brand
This file contains hidden or 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
<?php | |
// Include Stripe's library and set your API key. | |
require('./config.php'); | |
// Retrieve the account ID and amount details from your own database... | |
// Ex: $db is an object containing the attributes you retrieve from your database. | |
// Check for a submitted token | |
if (isset($_POST['stripeToken'])){ | |
// Retrieve the token from Stripe | |
$token = \Stripe\Token::retrieve($_POST['stripeToken']); | |
// Calculate the application fee based on the card brand | |
if ($token->card->brand == "American Express"){ | |
// Charge a 3.5% application fee for American Express | |
$application_fee = ($db->amount/100 * .035) * 100; | |
} | |
else { | |
// Charge 2.2% + $0.30 for everything else | |
$application_fee = ($db->amount/100 * .022 + .30) * 100; | |
} | |
// Create the charge | |
try { | |
$charge = \Stripe\Charge::create(array( | |
"amount" => $db->amount, // The total amount to charge the customer, in cents | |
"currency" => "usd", | |
"source" => $token, // The token submitted from Checkout or Stripe.js | |
"application_fee" => $application_fee, | |
"destination" => $db->connected_account_id, // The account ID, retrieved from your database | |
)); | |
$success = "Thanks! Your payment has been made"; | |
} | |
catch(\Stripe\Error\Card $e) { | |
// Since it's a decline, \Stripe\Error\Card will be caught | |
$body = $e->getJsonBody(); | |
$error = $body['error']['message']; // Display the $error message to the user in your app | |
} catch (\Stripe\Error\RateLimit $e) { | |
// Rate limits are pretty rare. Maybe have the user try again? | |
} catch (\Stripe\Error\InvalidRequest $e) { | |
// You made an invalid request to Stripe. Maybe log or send yourself an email? | |
} catch (\Stripe\Error\Authentication $e) { | |
// You used a bad API key | |
} catch (\Stripe\Error\ApiConnection $e) { | |
// There was a connectivity problem. Maybe log and have the user try again? | |
} catch (\Stripe\Error\Base $e) { | |
// Some other API error. Maybe log or send yourself an email? | |
} catch (Exception $e) { | |
// Something unrelated to Stripe happened. Log or send yourself an email, etc | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment