How can I integrate the escrow payment gateway in my custom payment method in Magento 2?
1 Answer
Vendor/Modulename/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Store/etc/config.xsd">
<default>
<payment>
<Modulenamepayment>
<model>Vendor\Modulename\Model\PaymentMethod</model>
<active>1</active>
<title>Modulename Payment</title>
<order_status>pending_payment</order_status><!-- set default order status-->
</Modulenamepayment>
</payment>
</default>
</config>
Vendor/Modulename/Model/PaymentMethod.php
<?php
namespace Vendor\Modulename\Model;
/**
* Pay In Store payment method model
*/
class PaymentMethod extends \Magento\Payment\Model\Method\AbstractMethod
{
/**
* Payment code
*
* @var string
*/
protected $_code = 'Modulenamepayment';
}
Vendor/Modulename/view/frontend/layout/checkout_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="checkout.root">
<arguments>
<argument name="jsLayout" xsi:type="array">
<item name="components" xsi:type="array">
<item name="checkout" xsi:type="array">
<item name="children" xsi:type="array">
<item name="steps" xsi:type="array">
<item name="children" xsi:type="array">
<item name="billing-step" xsi:type="array">
<item name="component" xsi:type="string">uiComponent</item>
<item name="children" xsi:type="array">
<item name="payment" xsi:type="array">
<item name="children" xsi:type="array">
<item name="renders" xsi:type="array">
<!-- merge payment method renders here -->
<item name="children" xsi:type="array">
<item name="Modulenamepayment" xsi:type="array">
<item name="component" xsi:type="string">Vendor_Modulename/js/view/payment/method-renderer</item>
<item name="methods" xsi:type="array">
<item name="Modulenamepayment" xsi:type="array">
<item name="isBillingAddressRequired" xsi:type="boolean">true</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</argument>
</arguments>
</referenceBlock>
</body>
</page>
Vendor/Modulename/view/frontend/web/js/action/set-payment-method-action.js
define(
[
'jquery',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/url-builder',
'mage/url',
'mage/storage',
'Magento_Checkout/js/model/error-processor',
'Magento_Customer/js/model/customer',
'Magento_Checkout/js/model/full-screen-loader'
],
function ($, quote, urlBuilder, url, storage, errorProcessor, customer, fullScreenLoader) {
'use strict';
return function (messageContainer) {
window.location.href = window.checkoutConfig.redirect_url;
};
}
);
Vendor/Modulename/view/frontend/web/js/view/payment/method-renderer/Modulenamepayment.js
define(
[
'Magento_Checkout/js/view/payment/default',
'Vendor_Modulename/js/action/set-payment-method-action'
],
function (Component,setPaymentMethodAction) {
'use strict';
return Component.extend({
defaults: {
redirectAfterPlaceOrder : false,
template: 'Vendor_Modulename/payment/Modulenamepayment'
},
afterPlaceOrder: function () {
setPaymentMethodAction(this.messageContainer);
return false;
}
});
}
);
Vendor/Modulename/view/frontend/web/js/view/payment/method-renderer.js
define(
[
'uiComponent',
'Magento_Checkout/js/model/payment/renderer-list'
],
function (
Component,
rendererList
) {
'use strict';
rendererList.push(
{
type: 'Modulenamepayment',
component: 'Vendor_Modulename/js/view/payment/method-renderer/Modulenamepayment'
}
);
return Component.extend({});
}
);
Vendor/Modulename/view/frontend/web/template/payment-method/Modulenamepayment.html
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio"
name="payment[method]"
class="radio"
data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>
<label data-bind="attr: {'for': getCode()}" class="label"><span data-bind="text: getTitle()"></span></label>
</div>
<div class="payment-method-content">
<!-- ko foreach: getRegion('messages') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->
<div class="payment-method-billing-address">
<!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->
</div>
<div class="actions-toolbar">
<div class="primary">
<button class="action primary checkout"
type="submit"
data-bind="
click: placeOrder,
attr: {title: $t('Place Order')},
css: {disabled: !isPlaceOrderActionAllowed()},
enable: (getCode() == isChecked())
"
disabled>
<span data-bind="i18n: 'Place Order'"></span>
</button>
</div>
</div>
</div>
</div>
Vendor/Modulename/Controller/Index/Index.php
<?php
namespace Vendor\Modulename\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Vendor\Modulename\Model\ModulenamePaymentFactory;
use Magento\Directory\Model\ResourceModel\Region\CollectionFactory;
class Index extends \Magento\Framework\App\Action\Action
{
protected $checkoutSession;
protected $customerFactory;
protected $resultRedirect;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Controller\ResultFactory $result,
ModulenamePaymentFactory $ModulenamePayment,
CollectionFactory $collectionFactory
) {
$this->_storeManager = $storeManager;
$this->checkoutSession = $checkoutSession;
$this->_customerFactory = $customerFactory;
$this->_ModulenamePayment = $ModulenamePayment;
$this->resultRedirect = $result;
$this->collectionFactory = $collectionFactory;
return parent::__construct($context);
}
/**
* Execute view action
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$incrementId = $this->checkoutSession->getLastRealOrderId();
$this->redirectToPaymentGateWay($incrementId);
}
/**
* Redirect to Payemnt Page
**/
public function redirectToPaymentGateWay($incrementId){
$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
$returnUrl = $baseUrl.'checkout\onepage\success';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($incrementId);
$getorderdata = $orderData->getData();
$orderItems = $orderData->getAllVisibleItems();
$itemData = array();
$productId = $seller_email = $itemQty = $itemDesc = $itemName = $itemPrice = '';
$buyer_email = $orderData->getCustomerEmail();
$vendor_commission_total = 20;
$order_name = $incrementId;
foreach($orderItems as $orderItems){
$productId = $orderItems->getProductId();
$product_collection_marketplace = $objectManager->create('Webkul\Marketplace\Model\Product')->load($productId,'mageproduct_id');
$sellerId = $product_collection_marketplace->getSellerId();
$seller = $this->_customerFactory->create()->load($sellerId);
$seller_email = $seller->getEmail();
$itemQty = $orderItems->getQtyOrdered();
$itemDesc = $orderItems->getDescription();
$itemName = $orderItems->getName();
$itemPrice = $orderItems->getRowTotal();
}
$address = $orderData->getShippingAddress()->getStreet();
$stateName = $orderData->getShippingAddress()->getRegion();
$regionArray = $this->getRegionCode($stateName);
/* New Code Satrt */
$request_array = array();
$request_array["currency"]="usd";
$request_array["items"][0]["description"]= $itemName;
$request_array["items"][0]["fees"][0]=array(
"payer_customer" => "me",
"split" => "1",
"type" => "Modulename"
);
$request_array["items"][0]["inspection_period"]="259200";
$request_array["items"][0]["quantity"]= floatval($itemQty);
$request_array["items"][0]["schedule"][0]=array(
"payer_customer"=>$buyer_email,
"amount"=>$itemPrice,
"beneficiary_customer"=>"me"
);
$request_array["items"][0]["title"] = $itemName;
$request_array["items"][0]["type"] = "general_merchandise";
$request_array["items"][1]["type"] = "shipping_fee";
$request_array["items"][1]["schedule"][0]=array(
"payer_customer"=>$buyer_email,
"amount"=>$orderData->getShippingAmount(),
"beneficiary_customer"=>"me"
);
$request_array["description"] = $itemName;
$request_array["parties"][0]=array(
"agreed"=>"1",
"customer"=>$buyer_email,
"role"=>"buyer",
"first_name"=>$orderData->getCustomerFirstname(),
"last_name"=>$orderData->getCustomerLastname(),
"phone_number"=>$orderData->getShippingAddress()->getTelephone()
);
$request_array["parties"][0]["address"]=array(
"line1"=> "address",
"line2" => "address",
"city" => $orderData->getShippingAddress()->getCity(),
"state" => $regionArray['region_id'],
"country" => $orderData->getShippingAddress()->getCountryId(),
"post_code" => $orderData->getShippingAddress()->getPostcode()
);
$request_array["parties"][1]=array(
"agreed" => "true",
"customer" => "me",
"initiator" => "true",
"role" =>"seller"
);
$request_array["return_url"] = $returnUrl;
/* New Code End */
$Modulename_email = Your Modulename account email id
$Modulename_api_key = Your Modulename account Api Key
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.Modulename-sandbox.com/integration/pay/2018-03-31",
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => TRUE,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $Modulename_email . ':' . $Modulename_api_key,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($request_array)
));
// Make the call to the Modulename.com API.
$output = curl_exec($curl);
// Get the HTTP status of the response.
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Close the curl command as we are done using it.
curl_close($curl);
$redirecturl= null;
$response = $array = json_decode($output);
$newdt = json_decode(json_encode($response), true);
if(isset($newdt['landing_page']) && isset($newdt['transaction_id'])) {
$redirecturl=$newdt['landing_page'];
?>
<script>
//document.getElementById("benifits-formsubmit").submit();
window.location.href = "<?php echo $redirecturl; ?>";
</script>
<?php
}else{
echo "error";
}
}
/**
* @param string $region
* @return string[]
*/
public function getRegionCode(string $region): array
{
$regionCode = $this->collectionFactory->create()
->addRegionNameFilter($region)
->getFirstItem()
->toArray();
return $regionCode;
}
}