use*_*921 15 php sql paypal magento coupon
我遇到了Magento单一优惠券代码的问题,该代码被标记为在客户点击"下订单"按钮时使用.如果Paypal付款失败或客户在订单完成之前离开页面,他将无法返回并重新订购此优惠券,该优惠券设置为仅使用一次,并且已标记已被使用.
我找到了一段代码,减少了用户使用优惠券的次数,并允许他重复使用优惠券.不幸的是,他在单击下订单按钮时尝试连接Paypal页面时出错.为了能够再次使用优惠券并访问Paypal页面,我必须使用此客户的ID 删除表salesrule_coupon_usage和salesrule_customer中SQL数据库中的行.
以下是我需要更改以自动删除客户ID的优惠券使用信息的代码:
public function cancel($observer)
{
$order = $observer->getEvent()->getPayment()->getOrder();
if ($order->canCancel()) {
if ($code = $order->getCouponCode()) {
$coupon = Mage::getModel('salesrule/coupon')->load($code, 'code');
if ($coupon->getTimesUsed() > 0) {
$coupon->setTimesUsed($coupon->getTimesUsed() - 1);
$coupon->save();
}
$rule = Mage::getModel('salesrule/rule')->load($coupon->getRuleId());
error_log("\nrule times used=" . $rule->getTimesUsed(), 3, "var/log/debug.log");
if ($rule->getTimesUsed() > 0) {
$rule->setTimesUsed($rule->getTimesUsed()-1);
$rule->save();
}
if ($customerId = $order->getCustomerId()) {
if ($customerCoupon = Mage::getModel('salesrule/rule_customer')->loadByCustomerRule($customerId, $rule->getId())) {
$couponUsage = new Varien_Object();
Mage::getResourceModel('salesrule/coupon_usage')->loadByCustomerCoupon($couponUsage, $customerId, $coupon->getId());
if ($couponUsage->getTimesUsed() > 0) {
/* I can't find any #@$!@$ interface to do anything but increment a coupon_usage record */
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$tableName = $resource->getTableName('salesrule_coupon_usage');
$query = "UPDATE {$tableName} SET times_used = times_used-1 "
. "WHERE coupon_id = {$coupon->getId()} AND customer_id = {$customerId} AND times_used > 0";
$writeConnection->query($query);
}
if ($customerCoupon->getTimesUsed() > 0) {
$customerCoupon->setTimesUsed($customerCoupon->getTimesUsed()-1);
$customerCoupon->save();
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我相信这是 1.4 到 1.6 左右的一个老错误。但无论您是否使用旧版本,如果您了解 Magento 的使用方法,都可以很容易地修复此问题。
问题是,当他们单击付款按钮时,您的代码会立即更新 salesrule_coupon_usage 表。这根本不是你想要的。您希望将其包含到付款交易中。我不知道这个错误是否是因为您有自定义代码或使用旧版本的 Magento 而发生的,但我会告诉您如何解决该问题。然后我会给你一个类似于你建议的修复方案:
Magento 已经有一个称为“事务”的抽象。事务用于将需要全部成功或全部失败的对象组合在一起,没有半途而废。Magento 将完成事务并尝试保存您放置在其中的每个对象。如果其中任何一个失败(例如,付款未通过),所有已保存的事件都将“回滚”。
幸运的是,Magento 已经创建了一个交易对象来处理支付成功后需要一起更新的各种事物的支付。您可以利用该交易并使用它来正确更新优惠券的使用情况。
这是您需要做的 10,000 英尺视图。
你完成了。事务将自动尝试保存已添加到其中的所有对象。如果任何部分失败(包括付款失败),它将回滚整个过程,并且您的优惠券将不会被使用。耶!
现在,在我看来,上述是处理该问题的最佳方法,但如果您由于某种原因遇到问题,这里有一个基于捕获不成功的付款然后使用您的代码的替代方法。
同样,这是 10,000 英尺的视图:
现在,当销售失败时,您可以返回并手动展开所有操作。这不像我的第一个解决方案那么干净,但根据您对 Magento 的熟悉程度,可能对您来说更容易。
我相当确定新的、干净的 Magento 版本不会有这个问题,所以让我提供一个相当明显的建议作为第三种解决方案。
祝你好运!