Skip to content

Instantly share code, notes, and snippets.

@adamjstevenson
Created September 21, 2016 22:25
Show Gist options
  • Save adamjstevenson/b20bd49c39e8743b0b271cd8f1a469b4 to your computer and use it in GitHub Desktop.
Save adamjstevenson/b20bd49c39e8743b0b271cd8f1a469b4 to your computer and use it in GitHub Desktop.
Create a charge with a custom tiered application fee
<?php
// Include Stripe's library and set your API key.
require('./config.php');
// Retrieve the account ID and application fee tier details from your own database...
// In this example $db is an object containing the attributes you retrieve from your database.
// Calculate the app fee to charge based on the pricing tier
if ($db->pricing_tier == 1){
// Charge 2.9% + $.30 per charge (passing Stripe's default processing fees)
$application_fee = ($db->amount/100 * .029 + .30) * 100;
}
elseif ($db->pricing_tier == 2){
// Charge 4% + $.50 per charge
$application_fee = ($db->amount/100 * .04 + .50) * 100;
}
elseif ($db->pricing_tier == 3){
// Charge 5% only per charge
$application_fee = ($db->amount/100 * .05) * 100;
}
// Check for a submitted token
if (isset($_POST['stripeToken'])){
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