Magento2 Shopping Cart Add Payment method Tutorial

Source: Internet
Author: User
Tags getmessage php file sprintf xmlns magento2

Magento2 Add Payment way payment method, see effect chart first


One: Startup file \app\code\inchoo\stripe\etc\module.xml

<?xml version= "1.0"?>
<config xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= ". /.. /.. /.. /.. /lib/internal/magento/framework/module/etc/module.xsd ">
<module name= "more_payment" schema_version= "1.0.0.0" active= "true" >
<sequence>
<module name= "Magento_sales"/>
<module name= "Magento_payment"/>
</sequence>
<depends>
<module name= "Magento_sales"/>
<module name= "Magento_payment"/>
</depends>
</module>
</config>

II: Configuration file config.xml \app\code\inchoo\stripe\etc\config.xml

<?xml version= "1.0"?>
<config xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= ". /.. /.. /magento/core/etc/config.xsd ">
<default>
<payment>
<more_payment>
<active>1</active>
<model>More\Payment\Model\Payment</model>
<payment_action>authorize_capture</payment_action>
<title>Payment</title>
<api_key backend_model= "magento\backend\model\config\backend\encrypted"/>
<cctypes>AE,VI,MC,DI,JCB</cctypes>
<allowspecific>1</allowspecific>
<min_order_total>0.50</min_order_total>
</more_payment>
</payment>
</default>
</config>

Three: Background configuration file App\code\inchoo\stripe\etc\adminhtml\system2.xml

<?xml version= "1.0"?>
<config xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:nonamespaceschemalocation= ". /.. /.. /.. /magento/backend/etc/system_file.xsd ">
<system>
<section id= "Payment" translate= "label" type= "text" sortorder= "" showindefault= "1" showinwebsite= "1" Showinstore= "1" >
<group id= "More_payment" translate= "label" type= "text" sortorder= "" showindefault= "1" showinwebsite= "1" Showinstore= "1" >
<label>Payment</label>

<field id= "Active" translate= "label" type= "select" sortorder= "1" showindefault= "1" showinwebsite= "1" showinstore= " 0 ">
<label>Enabled</label>
<source_model>Magento\Backend\Model\Config\Source\Yesno</source_model>
</field>
<field id= "title" translate= "label" type= "Text" sortorder= "2" showindefault= "1" showinwebsite= "1" showinstore= "1" >
<label>Title</label>
</field>
<field id= "Api_key" translate= "label" type= "Obscure" sortorder= "3" showindefault= "1" showinwebsite= "1" showInStore = "0" >
<label>api key</label>
<backend_model>Magento\Backend\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id= "Debug" translate= "label" type= "select" sortorder= "4" showindefault= "1" showinwebsite= "1" showinstore= "0 ">
<label>Debug</label>
<source_model>Magento\Backend\Model\Config\Source\Yesno</source_model>
</field>
<field id= "Cctypes" translate= "label" type= "MultiSelect" sortorder= "5" showindefault= "1" showinwebsite= "1" Showinstore= "0" >
<label>credit Card types</label>
<source_model>More\Payment\Model\Source\Cctype</source_model>
</field>
<field id= "Sort_order" translate= "label" type= "text" sortorder= "" showindefault= "1" showinwebsite= "1" Showinstore= "0" >
<label>sort order</label>
</field>
<field id= "allowspecific" translate= "label" type= "Allowspecific" sortorder= "showindefault=" "1" showInWebsite= " 1 "showinstore=" 0 ">
<label>payment from applicable countries</label>
<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
</field>
<field id= "Specificcountry" translate= "label" type= "MultiSelect" sortorder= "Wuyi" showindefault= "1" showInWebsite= " 1 "showinstore=" 0 ">
<label>payment from specific countries</label>
<source_model>Magento\Directory\Model\Config\Source\Country</source_model>
</field>
<field id= "Min_order_total" translate= "label" type= "text" sortorder= "" showindefault= "1" showinwebsite= "1" Showinstore= "0" >
<label>minimum Order total</label>
</field>
<field id= "Max_order_total" translate= "label" type= "text" sortorder= "" "showindefault=" 1 "showinwebsite=" 1 " Showinstore= "0" >
<label>maximum Order total</label>
<comment>leave Empty to disable limit</comment>
</field>
</group>
</section>
</system>
</config>

Four: Model class because we configured model in the Config.xml, so the front click Save Payment method to trigger

<?php

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 ');
}

/**
* Payment Capture Method
* *
* @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;
}
}




add some information to the credit card payment method in Magento

In the system-provided functionality, only < credit card holders >, credit card numbers, expiration dates, CVV, but in actual use, will require more information. Such as: The postal code of the credit card holder, the street address, the state and so on. When brushing a customer's credit card, it is prudent to expect it to be successful only if the information is exactly the same as the information registered on the credit card. So add some extra information. Here's how to add a zip code to the credit card payment information.

Previous job: Add a field to the Sales_flat_quote_payment first, zipcode

Train of thought: need first from Ajax as a clue, find the relevant template files, and then modify the program to achieve zipcode data preservation

1. Find the template used in payment first to Saveshippingmethodaction, obviously, it's _getpaymentmethodshtml's work.

protected function _getpaymentmethodshtml ()
{
$layout = $this->getlayout ();
$update = $layout->getupdate ();
$update->load (' Checkout_onepage_paymentmethod ');
$layout->generatexml ();
$layout->generateblocks ();
$output = $layout->getoutput ();
return $output;
}

2. Under the Layout folder of your current template, find checkout.xml File open, find

<checkout_onepage_paymentmethod>
<remove name= "right"/>
<remove name= "left"/>
<block type= "Checkout/onepage_payment_methods" name= "root" output= "toHtml" "template=" checkout/onepage/payment/ Methods.phtml ">
<action method= "Setmethodformtemplate" ><method>purchaseorder</method><template>payment/ Form/purchaseorder.phtml</template></action>
</block>
</checkout_onepage_paymentmethod>

Found it was using a methods.phtml template.

3. Open methods.phtml, see the following

$html = $this->getchildhtml (' Payment.method. ') $_code)

Obviously, it is going to output the current template directory under payment/save/$_code.phtml (path based on Layout.xml setpaymentformtemplate get)

4. Open $_code.phtml, add a row of zipcode content

<li>
<div class= "Input-box" >
<label for= "<?php echo $_code >_zipcode" ><?php echo $this->__ (' zipcode ')?> <span-class= " Required ">*</span></label><br/>
<input type= "text" title= "<?php Echo $this->__ (' ZipCode ')?>" class= "Required-entry input-text" id= " PHP echo $_code >_zipcode "Name=" Payment[zipcode] "value=" <?php Echo $this->htmlescape ($this-> Getinfodata (' ZipCode '))?> "/>
</div>
</li>

The display section ends here, and the following starts to add code to save the postcode to the database


5. Find the Savepaymentaction method in app/code/core/mage/checkout/controllers/onepagecontroller.php

Public Function savepaymentaction () {
$result = $this->getonepage ()->savepayment ($data);
}

6. Analysis of Savepayment methods

app/code/core/mage/checkout/model/type/onepage.php

$payment = $this->getquote ()->getpayment ();
$payment->importdata ($data);

7. Analysis of ImportData methods

Note: Here we start with AOP, a crosscutting in ImportData, a process that is the payment preparesave process that is designed to encrypt the plaintext information of credit cards.

Public function ImportData (array $data)
{
$data = new Varien_object ($data);
Mage::d ispatchevent (
$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 are not available '));
}
$method->assigndata ($data);
/*
* Validating the payment data
*/
$method->validate ();
return $this;
}


Another important thing is $method->assigndata ($data), which performs the Assigndata method of the specified payment.

For example: The Assigndata way to pay for credit cards is

8. Modify the app/code/core/mage/payment/model/method/cc.php file

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.