我有一个使用 Stripe 处理订阅付款的网站。只有一种订阅类型。
我在 NetTuts 上关注 this tutorial 进行初始设置。
有一个表单可以很好地处理订阅,一切正常。客户要求提供优惠券代码。 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)
);
}
关于php - 在 Stripe 中使用优惠券代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15032918/