| Current Path : /var/www/html/app/code/FlipsDigital/HappyMind/Controller/Order/ |
| Current File : /var/www/html/app/code/FlipsDigital/HappyMind/Controller/Order/FormPost.php |
<?php
namespace FlipsDigital\HappyMind\Controller\Order;
use Magento\Framework\DataObject;
use FlipsDigital\HktGateway\Controller\Auth\Jwt;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Email\Sender\OrderSender;
class FormPost extends \Magento\Framework\App\Action\Action implements \Magento\Framework\App\Action\HttpPostActionInterface
{
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\ObjectManagerInterface $objectManagerInterface,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
\Magento\Customer\Model\Metadata\FormFactory $formFactory,
\Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Catalog\Model\ProductFactory $product,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\FlipsDigital\CustomerTextbookList\Model\CustomerTextbookListFactory $customerTextbookListFactory,
\FlipsDigital\TextbookList\Model\TextbookListFactory $textbookListFactory,
\FlipsDigital\TextbookListBook\Model\TextbookListBookFactory $textbookListBookFactory,
\Magento\Framework\Session\SessionManagerInterface $coreSession,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\FlipsDigital\HktGateway\Model\PaymentLogFactory $paymentLogFactory,
OrderRepositoryInterface $orderRepository,
OrderSender $orderSender,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
\FlipsDigital\HktGateway\Helper\PaymentConfigData $paymentConfigData
) {
$this->_objectManager = $objectManagerInterface;
$this->_customerSession = $customerSession;
$this->_formKeyValidator = $formKeyValidator;
$this->_formFactory = $formFactory;
$this->resultForwardFactory = $resultForwardFactory;
$this->resultPageFactory = $resultPageFactory;
$this->_ctlFactory = $customerTextbookListFactory;
$this->_tlFactory = $textbookListFactory;
$this->_tlbFactory = $textbookListBookFactory;
$this->_storeManager = $storeManager;
$this->customerRepository = $customerRepository;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->_product = $product;
$this->_coreSession = $coreSession;
$this->_scopeConfig = $scopeConfig;
$this->_paymentLogFactory = $paymentLogFactory;
$this->orderRepository = $orderRepository;
$this->orderSender = $orderSender;
$this->timezone = $timezone;
$this->paymentConfigData = $paymentConfigData;
parent::__construct($context);
}
protected function _getSession()
{
return $this->_customerSession;
}
protected function _buildUrl($route = '', $params = [])
{
/** @var \Magento\Framework\UrlInterface $urlBuilder */
$urlBuilder = $this->_objectManager->create(\Magento\Framework\UrlInterface::class);
return $urlBuilder->getUrl($route, $params);
}
public function execute()
{
$params = $this->getRequest()->getParams();
$queryData = [
'id' => $this->getRequest()->getParam('id'),
'textbook' => $this->getRequest()->getParam('textbook'),
];
$payment_method = $this->getRequest()->getParam('payment_method');
$redirectUrl = null;
if (!$this->_customerSession->isLoggedIn()){
return $this->resultRedirectFactory->create()->setUrl($this->_buildUrl('customer/account/index'));
}
$redirectBack = false;
if (
!$this->_formKeyValidator->validate($this->getRequest()) ||
!$this->getRequest()->isPost() ||
empty($params['id']) ||
empty($params['textbook'])
) {
$redirectBack = true;
}
$objTL = $this->_tlFactory->create();
$objTLB = $this->_tlbFactory->create();
$objCTL = $this->_ctlFactory->create();
$objCustomerTextbookList = $objCTL->load($params['id']);
if (!$objCustomerTextbookList){
$redirectBack = true;
}
$childrenIdentifier = base64_decode($params['textbook']);
if ($objCustomerTextbookList->getIdentifier() != $childrenIdentifier){
$redirectBack = true;
}
if ($redirectBack) {
return $this->resultRedirectFactory->create()->setUrl(
$this->_redirect->error($this->_buildUrl('*/*/form', $queryData))
);
}
$objTextbookList = $objTL->load($objCustomerTextbookList->getData('booklist_id'));
$FormData = $this->getRequest()->getPostValue();
$collectionTLB = $objTLB->getCollection();
$collectionTLB->addAttributeToSelect('*');
$collectionTLB->addAttributeToFilter('booklist_id', $objCustomerTextbookList->getData('booklist_id'));
$collectionTLB->addAttributeToFilter('status', 1);
if ($collectionTLB->count()){
$store = $this->_storeManager->getStore();
$quote = $this->quote->create();
$quote->setStore($store);
$customer = $this->customerRepository->getById($this->_customerSession->getCustomer()->getId());
$quote->setCurrency();
$quote->assignCustomer($customer);
$arrProductId = [];
$allowPriceNotBuyAll = false;
if ($collectionTLB->count() != count($FormData['textbook_list_book'])){
$allowPriceNotBuyAll = true;
foreach ($collectionTLB->getItems() as $key => $value) {
if ($value->getData('price_not_buy_all') <=0 ){
$allowPriceNotBuyAll = false;
break;
}
}
}
foreach ($collectionTLB->getItems() as $key => $value) {
$product = $this->_product->create()->load($value->getData('product_id'));
if($value->getData('price_original') <= $value->getData('price_selling')){
$product->setPrice($value->getData('price_selling'));
}else{
$product->setPrice($value->getData('price_original'));
}
if (!$allowPriceNotBuyAll){
$specialPrice = $value->getData('price_selling');
$product->setSpecialPrice($specialPrice);
}else{
$specialPrice = $value->getData('price_not_buy_all');
$product->setPrice($specialPrice);
$product->setSpecialPrice($specialPrice);
}
$qty = 0;
if (
in_array($value->getData('product_id'), $FormData['textbook_list_book']) ||
$value->getData('must_buy')
){
$qty = 1;
}
if ($qty){
// $product->setSpecialPrice($specialPrice);
$quote->addProduct(
$product,
new DataObject([
'qty' => $qty,
])
);
}
}
$shippingAddress = [
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => 'HK',
'city' => 'HK',
'country_id' => 'HK',
'telephone' => '00000000',
];
$quote->getBillingAddress()->addData($shippingAddress);
$quote->getShippingAddress()->addData($shippingAddress);
// Collect Rates and Set Shipping & Payment Method
$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping');
$quote->setPaymentMethod('checkmo'); //payment method
$quote->setInventoryProcessed(false); //not effetc inventory
// $quote->setFeeAmount(0.3);
$quote->save(); //Now Save quote and your quote is ready
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => 'checkmo']);
$this->_coreSession->start();
$this->_coreSession->setCustomerTextbookListId($objCustomerTextbookList->getId());
$quote->collectTotals();
if (
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy') &&
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount')
) {
$plastic_bag_levy = $objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount');
$quote->setGrandTotal($quote->getGrandTotal() + $plastic_bag_levy);
$quote->setBaseGrandTotal($quote->getBaseGrandTotal() + $plastic_bag_levy);
//$quote->setSubtotal($quote->getSubtotal() + $plastic_bag_levy);
//$quote->setBaseSubtotal($quote->getBaseSubtotal() + $plastic_bag_levy);
//$quote->setSubtotalWithDiscount($quote->getSubtotalWithDiscount() + $plastic_bag_levy);
//$quote->setBaseSubtotalWithDiscount($quote->getBaseSubtotalWithDiscount() + $plastic_bag_levy);
}
$quote->save();
$order = $this->quoteManagement->submit($quote);
$order->setEmailSent(0);
$orderTotal = $order->getGrandTotal();
if (
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy') &&
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount')
) {
$plastic_bag_levy = $objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount');
$orderTotal += $plastic_bag_levy;
// $order->setGrandTotal($order->getGrandTotal() + $plastic_bag_levy);
// $order->setBaseGrandTotal($order->getBaseGrandTotal() + $plastic_bag_levy);
//$order->setSubtotal($order->getSubtotal() + $plastic_bag_levy);
//$order->setBaseSubtotal($order->getBaseSubtotal() + $plastic_bag_levy);
//$order->setSubtotalInclTax($order->getubtotalInclTax() + $plastic_bag_levy);
//$order->setBaseSubtotalInclTax($order->getBaseSubtotalInclTax() + $plastic_bag_levy);
// $order->setTotalDue($order->getTotalDue() + $plastic_bag_levy);
// $order->setBaseTotalDue($order->getBaseTotalDue() + $plastic_bag_levy);
}
switch($payment_method) {
case 'payment_alipay_hk':
case 'payment_alipay_cn':
$alipayHandlingCharge = $this->paymentConfigData->getHandlingChargeConfig('payment_alipay');
$handling_charge = $alipayHandlingCharge > 0 ? $alipayHandlingCharge : 0;
break;
case 'payment_tng_fps':
$tngHandlingCharge = $this->paymentConfigData->getHandlingChargeConfig('payment_tng_fps');
$handling_charge = $tngHandlingCharge > 0 ? $tngHandlingCharge : 0;
break;
case 'payment_wechatpay':
$wechatpayHandlingCharge = $this->paymentConfigData->getHandlingChargeConfig('payment_wechatpay');
$handling_charge = $wechatpayHandlingCharge > 0 ? $wechatpayHandlingCharge : 0;
break;
case 'payment_visa_master':
$cardHandlingCharge = $this->paymentConfigData->getHandlingChargeConfig('payment_visa_master');
$handling_charge = $cardHandlingCharge > 0 ? $cardHandlingCharge : 0;
break;
default:
$handling_charge = 0;
}
if($handling_charge) {
$handling_charge = round(($order->getGrandTotal()*($handling_charge/100)), 2);
}
$order->setShippingAmount($handling_charge);
$order->setBaseShippingAmount($handling_charge);
$orderTotal += $handling_charge;
$order->setGrandTotal($orderTotal);
$order->setBaseGrandTotal($orderTotal);
$order->setTotalDue($orderTotal);
$order->setBaseTotalDue($orderTotal);
$order->save();
$order_id = $order->getId();
// Custom Payment Methods
$arrCTLData = $objCustomerTextbookList->getData();
$merchantTransactionId = 'HMOBS'.$order_id.time();
$onlinePayment = true;
if($payment_method == 'payment_711'){
$onlinePayment = false;
$arrCTLData['order_id'] = $order_id;
$arrCTLData['payment_method'] = '711';
$arrCTLData['payment_amount'] = '';
$arrCTLData['prepare_oder_id'] = '';
$arrCTLData['transaction_id'] = '';
$arrCTLData['hkt_reference_id'] = '';
$arrCTLData['payment_status'] = '';
}else{
$arrCTLData['payment_method'] = $payment_method;
$arrCTLData['prepare_oder_id'] = $order_id;
$arrCTLData['transaction_id'] = $merchantTransactionId;
$arrCTLData['hkt_reference_id'] = $merchantTransactionId;
$arrCTLData['payment_status'] = 'pending';
}
if (
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy') &&
$objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount')
) {
$arrCTLData['plastic_bag_levy'] = $objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy');
$arrCTLData['plastic_bag_levy_amount'] = $objTextbookList->getData('mers_stock_source_g_gl_plastic_bag_levy_amount');
}
$objCustomerTextbookList->setData($arrCTLData);
$objCustomerTextbookList->save();
if($onlinePayment){
$paymentCurrency = 'HKD';
$paymentTotal = $orderTotal;
$return_url = $this->_buildUrl('*/*/success', $queryData);
$requestData = [
'currency' => $paymentCurrency,
'chargeTotal' => $paymentTotal,
'merchantTransactionId' => $merchantTransactionId,
];
$arrData['create_at'] = $this->timezone->date()->format('Y-m-d H:i:s');
if($payment_method == 'payment_tng_fps'){
// Production - support FPS
$app_id = '6298738225';
$app_secret = 'EJb+j4zUZyxAG6WgS3rbbbLErJUAUh++idbTygD1BTS8IoxFSXOcxGvh3Efg5QVx+VkKSXHV5ZFHb4viIkkD4w==';
$public_key = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAn5HOyqvf5MJon7qktLaxXQ8vkI/Z0cvsp8MjkZU9ZY2PFiXr7shumVFM9k3gIKzpplkWywC01cBoWLiIGD+UCxkqm/tnivDzFTLNf3xucPMJWqTmnj66IdZu4+msv4UVgv2Y00tfXBtr+eqYSif9SDNmyQ/ceHwHBZisnQB9mQil1HIdvEi62X3+l8EDOd3bYoxMQ54s4RfLdX8feww2Cfir98hTaFBdW77ETKfrca7sy6+i6Uo59IOlUZvmSz7Nor3oJsvdw0Ga2yrPD//A6w+Z6E1FtwK8Ug7U9pPfpf+o249U9AUj2w92K5Pbi6kEgkmfF8XlsipHuTwcwRJqqHEv5j6JdYAZcUZAl+s9iWE83eff3fSv19ope1FhbOzuFVYgEl97BAUOVDyENtSnLqY5zM8bfdtJxzrafMdDCUMq/hbgfiSB6e13s+SCxwqxBFOfDgQwNQqSjcXc47z0VCMHnWqdg9x3QihrSTa2khxgZtTTLsm/opB7GR1OEdtqPKg43xSUHQsjL866JkGCmHYn2ey6LVxDB6crVkdHtDmbfyyfW+oF81iqYzvAIIjSJmj82Dlv5SG9xVvVHzAJ7MdZyU02XcCXaFmEXuBrFEHeULrUCh70RosvRJtyk18xB4ST3INctqP6rFkzA00FyZZ0nrPPbQqc+HQwaswVqGkCAwEAAQ==';
$api_url = 'https://gateway2.tapngo.com.hk/web/payments';
// // UAT
// $app_id = '4278527199';
// $app_secret = '4qt3IzuyeTiznf8A8vG8zkvS+K/24YqLjmtIVI+hYXpCfqYau8kuzw/I2zwxay0K83ihsAwa9CinqnZlhwO/wg==';
// $public_key = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs4YU4S9UfZNyl0V0s7fMTU71fJCvRb7yFhz3eNDnd+mazKYSQEo/BOEWrtcTSaioXLAu+EYIVXpbXYhd0rIjBhbwD6aw7QW57NBMD+i0L2rbRV+R3sCzfaDduWtQtdr1bYi8Bg1Oozmzjva3cSK8SetURi6QPr4Yakr0nfo8/y+0fu7FkUGGQT4uIzjleSmqJGZWnNRKLrEp+27i4C0uK1VuwQwmpWhs9ZoFs2cIG8+7GaMEFUPW/YMlgPL36yKqVcdthqxOM7bO0lsr/FWF2FTtNoX/CMUyIbfI10f+sBTRxIIGcHf8sbe4w7IGF9xMTVYSrSTYYnPflNxdfYR+/9CUxvNEW0niTfgV3fHN56Z22W62xOEa8ITsAKfNS+l6OBw5Jp7cNQzqjG3FA9CbyDgOMUfjobTAcvNL2+W58mybtsqj8c9SCdw38H3pC/HIdk+EyGdmfQRB2p1BbymgL+/5cf+OU1VjXuZaYljoOLVOG4clxaiEbYd+DJlaJm1sCFDHOuBrRSRIhMmbgPbaEczP6+IcRcGaJc1F9jermBay86eTAng4c8kb5vnwRB1noh7sZzeCSwCgJ23db1YzayNC8qqvNHikjLfHSXkOB8NrG8gqG/d21M9su82ACDpelUc6rN43Zxf3yrLbpEMGHbcFoUluI8oTL/IQTB8WkgkCAwEAAQ==';
// $api_url = 'https://gateway.sandbox.tapngo.com.hk/web/payments';
$merTradeNo = $merchantTransactionId;
$data = [];
$paymentInfo = [
"totalPrice" => $paymentTotal,
"currency" => $paymentCurrency,
"merTradeNo" => $merTradeNo,
// "notifyUrl" => "https://merchant.servers.domain.com/merchant/part/payment/some/path/leads/notify",
"returnUrl" => $this->_buildUrl('payment/callbacks/fps.php?id='.$queryData['id'].'&textbook='.$queryData['textbook']),
// "remark" => "This user has special request",
"lang" => "zh"
];
$paymentInfo = json_encode($paymentInfo);
$keyFinal = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split($public_key) . "-----END PUBLIC KEY-----";
if(openssl_public_encrypt($paymentInfo, $encrypted, $keyFinal, OPENSSL_PKCS1_OAEP_PADDING)){
$data['payload'] = base64_encode($encrypted);
}
// The parameters should be arranged in alphabetical order
$queryStr = 'appId='.$app_id.'&merTradeNo='.$merTradeNo.'&payload='.$data['payload'].'&paymentType=S';
$sign = hash_hmac('sha512', $queryStr, $app_secret, true);
$objPaymentLog = $this->_paymentLogFactory->create();
// $arrData['create_at'] = date('Y-m-d H:i:s');
$arrData['identifier'] = $merTradeNo;
$arrData['magento_order_id'] = $order_id;
$arrData['request_data'] = $paymentInfo;
$arrData['payment_status'] = 'Pending';
$arrData['payment_method'] = 'Tap & Go or FPS';
$objPaymentLog->setData($arrData);
$objPaymentLog->save();
echo '<form action="'.$api_url.'" method="post" id="tng_form" name="tng_form" style="display: none;">
<input type="hidden" name="appId" value="'.$app_id.'"/>
<input type="hidden" name="merTradeNo" value="'.$merTradeNo.'" />
<input type="hidden" name="payload" value="'.$data['payload'].'"/>
<input type="hidden" name="paymentType" value="S"/>
<input type="hidden" name="sign" value="'.base64_encode($sign).'"/>
<input type="submit" value="Pay By Tap & Go"/>
</form>';
echo '<script>document.getElementById("tng_form").submit();</script>';
return $redirectUrl;
}else{
switch($payment_method) {
case 'payment_alipay_hk':
$app_id = '0068808214';
$app_secret = 'dbzhfkGI2f3eOlwsqxhEABz7z1sn7PB9A5YG4VrDA7OAeQvL3GVArnemYkOeSHgdT9hD2CGR/nJYPjvG3OPhyw==';
$api_url = 'https://gateway2.tapngo.com.hk/ePaymentGateway/alipayhk/transactions/paymentUrl';
$requestData['customerId'] = '998794569';
$requestData['returnUrl'] = $return_url;
$arrData['payment_method'] = 'ALIPAYHK';
break;
case 'payment_alipay_cn':
$app_id = '7841813081';
$app_secret = '/P6yAbskjS0K25fH6Om8kxkdVgqpJRaarxpXNOmNoTmfSqvwaO3A+e4i0xzrnxDBE/1Np7a1r14uTwzcgTnGQA==';
$api_url = 'https://gateway2.tapngo.com.hk/ePaymentGateway/alipaycn/transactions/paymentUrl';
$requestData['customerId'] = '998794569';
$requestData['returnUrl'] = $return_url;
$arrData['payment_method'] = 'ALIPAYCN';
break;
case 'payment_visa_master':
$app_id = '8198364860';
$app_secret = 'YX8chyKVNHYKN2u2AXMynVoQEpAvvqYL86wNNIoPOz9aAdKBCG96xg+n7x4VdHaTQiv/wSPIIRQmi9pQvK9SNg==';
$api_url = 'https://gateway2.tapngo.com.hk//ePaymentGateway/visamastercard/v2/transactions/paymentUrl';
$requestData['customerId'] = '998794569';
$requestData['responseFailUrl'] = $this->_buildUrl('textbook/lists/index');
$requestData['responseSuccessUrl'] = $return_url;
$arrData['payment_method'] = 'Visa/Master';
break;
case 'payment_wechatpay':
$app_id = '2516279849';
$app_secret = 'CpswD/217CJqvCmaZqKpOkwhh4SyU0wlZX6OaW45tuC0gOro57RnMDu8LpBO9ma/v0ppmWEN8VtKrCmGOUIbSg==';
$api_url = 'https://gateway2.tapngo.com.hk/ePaymentGateway/wechatpay/transactions/qrCode';
$arrData['payment_method'] = 'WeChatPay';
break;
}
$payload = [
"sub" => $app_id,
"iat" => time()
];
$token = Jwt::getToken($payload, $app_secret);
$authorization = "Authorization: Bearer ".$token;
$ch = curl_init();
$options = [
CURLOPT_URL => $api_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($requestData),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
$authorization,
),
];
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
// $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$arrData['response_data'] = $response;
$response = json_decode($response, true);
$objPaymentLog = $this->_paymentLogFactory->create();
$arrData['identifier'] = $merchantTransactionId;
$arrData['magento_order_id'] = $order_id;
$arrData['request_data'] = json_encode($requestData);
$arrData['payment_status'] = 'Pending';
$objPaymentLog->setData($arrData);
$objPaymentLog->save();
$payment_url = $return_url;
if($response['status'] == '0'){
if(isset($response['payload']['paymentUrl'])){
$payment_url = $response['payload']['paymentUrl'];
}
switch($payment_method) {
case 'payment_alipay_hk':
case 'payment_alipay_cn':
case 'payment_wechatpay':
if(isset($response['payload']['paymentBrn'])){
$objCustomerTextbookList->setData('hkt_reference_id', $response['payload']['paymentBrn']);
}
break;
case 'payment_visa_master':
if(isset($response['payload']['orderId'])){
$objCustomerTextbookList->setData('hkt_reference_id', $response['payload']['orderId']);
}
break;
}
$objCustomerTextbookList->save();
}
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath($payment_url);
return $resultRedirect;
}
}else{
$order = $this->orderRepository->get($order_id);
$this->orderSender->send($order);
return $this->resultRedirectFactory->create()->setUrl(
$this->_redirect->error($this->_buildUrl('*/*/success', $queryData))
);
}
}
return $this->resultRedirectFactory->create()->setUrl(
$this->_redirect->error($this->_buildUrl('*/*/form', $queryData))
);
}
}