magento2开发教程_magento2购物车添加支付方式教程

时间:2019-12-02  来源:magento  阅读:

magento2 添加支付方式payment method,先看效果图

magento2-payment-method


一:启动文件 \app\code\Inchoo\Stripe\etc\module.xml















二:配置文件config.xml \app\code\Inchoo\Stripe\etc\config.xml






1
More\Payment\Model\Payment
authorize_capture
Payment

AE,VI,MC,DI,JCB
1
0.50





三:后台配置文件 app\code\Inchoo\Stripe\etc\adminhtml\system2.xml







 


Magento\Backend\Model\Config\Source\Yesno






Magento\Backend\Model\Config\Backend\Encrypted



Magento\Backend\Model\Config\Source\Yesno



More\Payment\Model\Source\Cctype






Magento\Payment\Model\Config\Source\Allspecificcountries



Magento\Directory\Model\Config\Source\Country






Leave empty to disable limit






四:model类 因为我们在config.xml配置了model,所以前台点击保存支付方式的时候 触发

 
namespace More\Payment\Model;
 
class Payment extends \Magento\Payment\Model\Method\Cc
{
const CODE = 'more_payment';
 
protected $_code = self::CODE;
 
protected $_isGateway = true;
protected $_canCapture = true;
protected $_canCapturePartial = true;
protected $_canRefund = true;
protected $_canRefundInvoicePartial = true;
 
protected $_stripeApi = false;
 
protected $_minAmount = null;
protected $_maxAmount = null;
protected $_supportedCurrencyCodes = array('USD');
 
public function __construct(
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Logger\AdapterFactory $logAdapterFactory,
\Magento\Framework\Logger $logger,
\Magento\Framework\Module\ModuleListInterface $moduleList,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Centinel\Model\Service $centinelService,
\Stripe\Api $stripe,
array $data = array()
) {
parent::__construct($eventManager, $paymentData, $scopeConfig, $logAdapterFactory, $logger, $moduleList, $localeDate, $centinelService, $data);
 
$this->_stripeApi = $stripe;
// $this->_stripeApi->setApiKey(
// $this->getConfigData('api_key')
// );
 
$this->_minAmount = $this->getConfigData('min_order_total');
$this->_maxAmount = $this->getConfigData('max_order_total');
}
 
/**
* 支付捕获方法
* *
* @param \Magento\Framework\Object $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Model\Exception
*/
public function capture(\Magento\Framework\Object $payment, $amount)
{
/** @var Magento\Sales\Model\Order $order */
$order = $payment->getOrder();
 
/** @var Magento\Sales\Model\Order\Address $billing */
$billing = $order->getBillingAddress();
 
try {
$charge = \Stripe_Charge::create(array(
'amount' => $amount * 100,
'currency' => strtolower($order->getBaseCurrencyCode()),
'description' => sprintf('#%s, %s', $order->getIncrementId(), $order->getCustomerEmail()),
'card' => array(
'number' => $payment->getCcNumber(),
'number' => $payment->getCcNumber(),
'exp_month' => sprintf('%02d',$payment->getCcExpMonth()),
'exp_year' => $payment->getCcExpYear(),
'cvc' => $payment->getCcCid(),
'name' => $billing->getName(),
'address_line1' => $billing->getStreet(1),
'address_line2' => $billing->getStreet(2),
'address_zip' => $billing->getPostcode(),
'address_state' => $billing->getRegion(),
'address_country' => $billing->getCountry(),
),
));
 
$payment
->setTransactionId($charge->id)
->setIsTransactionClosed(0);
} catch (\Exception $e) {
$this->debugData($e->getMessage());
$this->_logger->logException(__('Payment capturing error.'));
throw new \Magento\Framework\Model\Exception(__('Payment capturing error.'));
}
 
return $this;
}
 
/**
* Payment refund
*
* @param \Magento\Framework\Object $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Model\Exception
*/
public function refund(\Magento\Framework\Object $payment, $amount)
{
$transactionId = $payment->getParentTransactionId();
 
try {
\Stripe_Charge::retrieve($transactionId)->refund();
} catch (\Exception $e) {
$this->debugData($e->getMessage());
$this->_logger->logException(__('Payment refunding error.'));
throw new \Magento\Framework\Model\Exception(__('Payment refunding error.'));
}
 
$payment
->setTransactionId($transactionId . '-' . \Magento\Sales\Model\Order\Payment\Transaction::TYPE_REFUND)
->setParentTransactionId($transactionId)
->setIsTransactionClosed(1)
->setShouldCloseParentTransaction(1);
 
return $this;
}
 
/**
* Determine method availability based on quote amount and config data
*
* @param null $quote
* @return bool
*/
public function isAvailable($quote = null)
{
if ($quote && (
$quote->getBaseGrandTotal() < $this->_minAmount
|| ($this->_maxAmount && $quote->getBaseGrandTotal() > $this->_maxAmount))
) {
return false;
}
 
// if (!$this->getConfigData('api_key')) {
// return false;
// }
 
return parent::isAvailable($quote);
}
 
/**
* Availability for currency
*
* @param string $currencyCode
* @return bool
*/
public function canUseForCurrency($currencyCode)
{
if (!in_array($currencyCode, $this->_supportedCurrencyCodes)) {
return false;
}
return true;
}
}

 
 

在Magento中为信用卡支付方式添加一些信息

在系统提供的功能中,只有<信用卡持有者>、信用卡号、过期日期、CVV,但在实际使用中,会需要更多的信息。如:信用卡持有者的邮编、街道地址、所在州等。在刷客户信用卡时,出于谨慎,希望只有这些信息与信用卡上所登记的信息完全一致时,刷卡才能成功。所以要加一些额外信息。下面讲述的是如何添加一个邮编到信用卡支付信息中。

前题工作:先在sales_flat_quote_payment 中添加一字段,zipcode

思路:需要先要先从Ajax为线索,找到相关的模板文件,而后修改程序来实现对zipcode的数据保存

1.先到saveShippingMethodAction中找到payment所用的模板,很显然,是_getPaymentMethodsHtml起作用

protected function _getPaymentMethodsHtml()  
{  
    $layout = $this->getLayout();  
    $update = $layout->getUpdate();  
    $update->load('checkout_onepage_paymentmethod');  
    $layout->generateXml();  
    $layout->generateBlocks();  
    $output = $layout->getOutput();  
    return $output;  
}  

2.在您当前模板的layout文件夹下,找到checkout.xml文件打开,找一下

 
      
      
      
        purchaseorder  
    
 
 

发现它用的是methods.phtml模板

3.打开methods.phtml,看到如下

$html = $this->getChildHtml('payment.method.'.$_code)  

很显然,它是要输出当前模板目录下payment/save/$_code.phtml(路径根据layout.xml中setPaymentFormTemplate获取)

4.打开$_code.phtml,添加一行zipcode内容

 
    
      
 
        
    
 

显示部分到此结束,下面开始添加代码来实现把邮编保存到数据库

 
5.在app/code/core/Mage/Checkout/controllers/OnepageController.php中找到savePaymentAction方法

public function savePaymentAction(){  
    $result = $this->getOnepage()->savePayment($data);  
}  

6.分析savePayment方法

app/code/core/Mage/Checkout/Model/Type/Onepage.php

$payment = $this->getQuote()->getPayment();  
$payment->importData($data);  

7.分析importData方法

注意:这里开始用AOP了,即在importData中做了一个横切,插入一个过程,该过程就是payment的prepareSave过程,这个过程的作用就是为了把信用卡的明文信息加密。

public function importData(array $data)  
{  
   $data = new Varien_Object($data);  
   Mage::dispatchEvent(  
       $this->_eventPrefix . '_import_data_before',  
       array(  
           $this->_eventObject=>$this,  
           'input'=>$data,  
       )  
   );  
   $this->setMethod($data->getMethod());  
    
   $method = $this->getMethodInstance();  
   if (!$method->isAvailable($this->getQuote())) {  
       Mage::throwException(Mage::helper('sales')->__('Requested Payment Method is not available'));  
   }  
   $method->assignData($data);  
   /*
   * validating the payment data
   */  
   $method->validate();  
   return $this;  
}  


另一个比较重要的是$method->assignData($data),该语句的作用是执行指定payment的assignData方法。

例如 :信用卡支付方式的的assignData方法就是

8.修改app/code/core/Mage/Payment/Model/Method/Cc.php文件

public function assignData($data)  
{  
    if (!($data instanceof Varien_Object)) {  
        $data = new Varien_Object($data);  
    }  
    $info = $this->getInfoInstance();  
    $info->setCcType($data->getCcType())  
        ->setCcOwner($data->getCcOwner())  
        ->setCcLast4(substr($data->getCcNumber(), -4))  
        ->setCcNumber($data->getCcNumber())  
        ->setCcCid($data->getCcCid())  
        ->setZipcode($data->getZipcode())           
        ->setCcExpMonth($data->getCcExpMonth())  
        ->setCcExpYear($data->getCcExpYear());  
    return $this;  
}  


magento2开发教程_magento2购物车添加支付方式教程

http://m.bbyears.com/wangyezhizuo/81875.html

推荐访问:
相关阅读 猜你喜欢
本类排行 本类最新