Magento 0元订单支付方式 - Magento Free Payment Method

需求

现有购物网站支持2种支付方式,但是考虑到会出现如下情况: 在一个优惠活动中,假如有一些订单的总金额为0, 那么这些订单就不必跳转到支付网关,现有支付方式无法处理此种情况。

分析

当customer输入订单的收货信息后,点击确认按钮,页面就会跳转到选择支付方式页面,默认流程是直接给出所有支付方式供customer选择,但是对于上面需求中提到的情况:假如订单总金额为0,那么就不应该直接给出所有支付方式,因为根本没有支付需求嘛。修改后的流程应该是先检测订单总金额,假如订单总金额等于0,则只提供一种支付方式——Free Payment支付方式,供customer选择,Free Payment支付方式无需支付,在用户同意并点击checkout-agreements后直接将订单信息发送至服务器;假如订单总金额大于0,则返回全部原有的支付方式供customer选择(应除去新增的Free Payment支付方式)。

解决方案

我查看了Magento的Payment Module的源码之后,发现Magento1.9原生支持0金额订单支付(如果有经验的话根本不需要看源代码),在后台System->Configration->SALES->Payment Methods->Zero Subtotal Checkout可进行配置以开启此支付方式。

配置选项如下:

  1. “Title”控制前端显示的名称
  2. “New Order Status”表示通过此方式支付后的订单状态
  3. “Automatically Invoice All Items”:自动invoice订单内包含的所有项目
  4. 通过配置这些参数,就可以实现上面提出的需求。

源码分析

下面记录了一下我查看Magento支付模块(Payment Module)源码的过程:

Magento返回支付方式是在的URL是base_url/checkout/onepage/saveShippingMethod/, 可以看出,这个动作是在onepageController中的saveShippingMethodAction()方法中完成的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//file: base_dir/app/code/core/Mage/Checkout/controllers/onepageController.php
/**
 * Shipping method save action
 */
public function saveShippingMethodAction()
{
    if ($this->_expireAjax()) {
        return;
    }
    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost('shipping_method', '');
        $result = $this->getOnepage()->saveShippingMethod($data);
        // $result will contain error data if shipping method is empty
        if (!$result) {
            Mage::dispatchEvent(
                'checkout_controller_onepage_save_shipping_method',
                array(
                    'request' => $this->getRequest(),
                    'quote' => $this->getOnepage()->getQuote()));
            $this->getOnepage()->getQuote()->collectTotals();
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

            $result['goto_section'] = 'payment';
            $result['update_section'] = array(
                'name' => 'payment-method',
                'html' => $this->_getPaymentMethodsHtml()
            );
        }
        $this->getOnepage()->getQuote()->collectTotals()->save();
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
}

在这个方法中,首先获取了POST过来的 “shipping_method” 数据,检测有否有error,如果没有error就生成$result数组,最后在 Mage_Core_Helper_Data 类的 jsonEncode() 方法中将$result数组编码为JSON格式,最后发送到浏览器。

生成$result[‘update_section’][‘html’]的方法$this->_getPaymentMethodsHtml()代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//file: base_dir/app/code/core/Mage/Checkout/controllers/onepageController.php
/**
 * Get payment method step html
 *
 * @return string
 */
protected function _getPaymentMethodsHtml()
{
    $layout = $this->getLayout();
    $update = $layout->getUpdate();
    $update->load('checkout_onepage_paymentmethod');
    $layout->generateXml();
    $layout->generateBlocks();

    //---------only for debug------------------
    /** @var Mage_Core_Block_Template $block */
    foreach ($layout->getAllBlocks() as $block) {
        Mage::log($block->getTemplate());
    }
    //---------only for debug------------------

    $output = $layout->getOutput();
    return $output;
}

此方法生成了供前台页面使用的HTML。可以通过做Log来快速定位PaymentMethod Block的Template。其中,$layout为 Mage_Core_Model_Layout 的实例,查看它的 getOutput() 方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
//file: base_url/app/code/core/Mage/Core/Model/Layout.php
/**
 * Get all blocks marked for output
 *
 * @return string
 */
public function getOutput()
{
    $out = '';
    if (!empty($this->_output)) {
        foreach ($this->_output as $callback) {
            //---------only for debug------------------
            Mage::log($callback)
        Mage::log(get_class($this->getBlock($callback[0])));
        Mage::log($this->getBlock($callback[0])->getTemplate());
        //---------only for debug------------------
        $out .= $this->getBlock($callback[0])->$callback[1]();
     }
    }

    return $out;
}

通过对$callback做log,可以知道$callback的结构如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//Mage::log($callback);
Array
(
    [0] => root
    [1] => toHtml
)
//Mage::log(get_class($this->getBlock($callback[0])));
Mage_Checkout_Block_Onepage_Payment_Methods
//Mage::log($this->getBlock($callback[0])->getTemplate());
checkout/onepage/payment/methods.phtml

进而可以知道Payment Methods的Block是 Mage_Checkout_Block_Onepage_Payment_Methods (如果你有经验的话应该早就猜到了是这个Block了,Magento是通过Block和template文件结合起来渲染页面的)。 结合 Mage_Checkout_Block_Onepage_Payment_Methods 和它的Template文件, 可以确定它是通过 getMethods() 这个方法来获取合适的支付方式的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//file: base_dir/app/code/core/Mage/Payment/Block/Form/Container.php
/**
 * Retrieve available payment methods
 *
 * @return array
 */
public function getMethods()
{
    $methods = $this->getData('methods');
    if ($methods === null) {
        $quote = $this->getQuote();
        $store = $quote ? $quote->getStoreId() : null;
        $methods = array();
        foreach ($this->helper('payment')->getStoreMethods($store, $quote) as $method) {
            if ($this->_canUseMethod($method) && $method->isApplicableToQuote(
                    $quote,
                    Mage_Payment_Model_Method_Abstract::CHECK_ZERO_TOTAL
                )
            ) {
                $this->_assignMethod($method);
                $methods[] = $method;
            }
        }
        $this->setData('methods', $methods);
    }
    return $methods;
}

在 getMethods() 中,一共有三种方式可以控制某个quote的支付方式:

第一种是$this->helper(‘payment’)->getStoreMethods($store, $quote),这个是“源头”; 第二个是$this->_canUseMethod($method); 第三个是$method->isApplicableToQuote($quote, Mage_Payment_Model_Method_Abstract::CHECKZEROTOTAL); 结合这三种方式,就可以筛选出合适的支付方式。假如你新增了一种支付方式,但是前台显示不出来,就应该从这三个筛选方式着手。

这次的Magento源码“探索之旅”就到这里吧 😀

Built with Hugo
主题 StackJimmy 设计