[英]Using Coupon Codes with Stripe
我有一个使用Stripe处理订阅付款的网站。 订阅只有一种。 我按照NetTuts上的本教程进行了初始设置。 有一个表格可以很好地处理订阅,并且一切正常。 客户要求输入优惠券代码。 Stripe支持此功能,因此我着手尝试将优惠券代码添加到现有表单中。
我在Stripe中设置优惠券代码,设置测试键,并在Stripe中切换到测试模式。 我在代码中执行了几项检查:
如果输入了优惠券并且有效,则在创建新客户时将匹配的Stripe优惠券对象作为选项传递。
if(isset($couponCode) && strlen($couponCode) > 0) {
$using_discount = true;
try {
$coupon = Stripe_Coupon::retrieve($couponCode);
if($coupon !== NULL) {
$cCode = $coupon;
}
// if we got here, the coupon is valid
} catch (Exception $e) {
// an exception was caught, so the code is invalid
$message = $e->getMessage();
returnErrorWithMessage($message);
}
}
try
{
if($using_discount == true) {
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => "basic_plan",
"email" => $email,
"coupon" => $cCode
));
}
else {
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => "basic_plan",
"email" => $email
));
}
$ couponCode正确填充了表单字段,就像填充其他所有字段一样,我已经三重检查了它是否被正确拉出。
当我尝试提交没有优惠券代码的表格时,它将收取全额费用并正确通过Stripe。
但是,如果我输入有效或无效的优惠券代码,则在创建新的客户对象时,它不会将优惠券对象与客户对象一起传递,并且在通过Stripe时收取全额费用。
我看了几个小时的代码,似乎无法弄清楚为什么它总是无法识别折扣代码并将匹配的优惠券对象传递给Stripe。
这可能有点过时,您找到了代码的解决方案。 但是,您似乎需要做的就是传递原始的$ couponCode作为Coupon的数组值。 正如codasaurus所说,您只是从优惠券的条带中获得了一个数组,除非您执行了$ cCode-> id并将ID传递回您的数组以创建客户,否则您不需要使用该数组。
当您将$ using_discount设置为true时,我进行了更改,因为如果优惠券有效,这将触发发送优惠券代码。
一旦优惠券实际有效,我们就发送优惠券。 您只需要提交状态的值,因此$ coupon是那里系统折扣的参考。 或者,如果您要使用$ coupon-> id进行创建,则可以使用它。
这是我根据您的代码提出的解决方案,可能会更好,但是我希望它可以帮助其他人寻找像我这样的解决方案。
if($coupon!='' && strlen($coupon) > 0) {
try {
$coupon = Stripe_Coupon::retrieve($coupon); //check coupon exists
if($coupon !== NULL) {
$using_discount = true; //set to true our coupon exists or take the coupon id if you wanted to.
}
// if we got here, the coupon is valid
} catch (Exception $e) {
// an exception was caught, so the code is invalid
$message = $e->getMessage();
returnErrorWithMessage($message);
}
}
if($using_discount==true)
{
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
"email" => $id,
"coupon"=>$coupon) //original value input example: "75OFFMEMBER" stripe should be doing the rest.
);
}
else
{
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
"email" => $id)
);
}
查看文档https://stripe.com/docs/api#create_customer,Stripe_Customer :: create()调用仅在查找优惠券代码。 您好像正在传递整个优惠券对象。
除非您的第一次尝试失败,否则$ couponCode已包含您的优惠券代码。 此外,您还需要执行其他几项检查来确定优惠券是否有效。 例如,如果coupon-> times_redeemed <coupon-> max_redemptions,或者如果coupon-> redeem_by已通过,等等。您可能还想通过检查客户折扣对象来检查客户是否已经在使用该优惠券。
如果以上任何一项检查失败,则只需将$ using_discount = false设置为;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.