Created
May 17, 2017 01:10
-
-
Save jake-yeg/e0b6cfe425b1b01b87a7dd3882b9a69d to your computer and use it in GitHub Desktop.
Coupon Recipe - PHP
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
Managing coupons on the server | |
---------------- | |
<?php | |
$private_key = 'sk_test_xxxxx'; | |
$amount = 500; | |
$final_amount = ''; | |
$coupon = $_POST['couponCode']; | |
function get_discount($coupon){ | |
$coupons = [ | |
'coupon1' => 0.15, | |
'coupon2' => 0.25 | |
]; | |
if(isset($coupons[$coupon])){ | |
return $coupon[$coupon]; | |
}else{ | |
return false; | |
} | |
} | |
if(!empty($coupon)){ | |
$discount = get_discount($coupon); | |
if(!discount){ | |
echo 'Error: Coupon is invalid.'; | |
}else{ | |
$discount_amount = $amount * $discount; | |
$final_amount = $amount - $discount_amount; | |
$metadata = [ | |
'coupon' => $coupon, | |
'amount' => $discount_amount | |
]; | |
} | |
} | |
try{ | |
$customer = \Stripe\Customer::create(array( | |
'email' => $_POST['stripeEmail'], | |
'source' => $_POST['stripeToken'] | |
)); | |
$charge = \Stripe\Charge::create(array( | |
'amount' => $final_amount, | |
'customer' => $customer->id, | |
'description' => 'PHP Example', | |
'metadata' => $metadata, | |
'currency' => 'usd' | |
)); | |
}catch(\Exception $e){ | |
//Var dump during DEV only; switch to something like error_log($e) later. | |
var_dump($e); | |
} | |
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
Adding a form field | |
------------------- | |
<?php | |
$public_key = 'pk_test_xxxxxx'; | |
$charge_endpoint = '/charge.php'; | |
?> | |
<form action="<?= $charge_endpoint ?>" method="POST"> | |
<p> | |
<label class="amount"> | |
<span>Amount: $5.00</span> | |
</label> | |
</p> | |
<p> | |
<label for="couponCode">Coupon</label><input type="text" name="couponCode" id="couponCode" /> | |
</p> | |
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" | |
data-key="<?= $public_key ?>" | |
data-description="Your Purchase" | |
data-locale="auto"></script> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment