Skip to content

Commit

Permalink
payment successful
Browse files Browse the repository at this point in the history
  • Loading branch information
mister-teddy committed Jul 21, 2021
1 parent 5bfeffd commit 294fbbf
Show file tree
Hide file tree
Showing 6 changed files with 232 additions and 122 deletions.
89 changes: 89 additions & 0 deletions zalopay/controllers/front/callback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/

/**
* @since 1.5.0
*/
class ZaloPayCallbackModuleFrontController extends ModuleFrontController
{
/**
* @see FrontController::postProcess()
*/
public function postProcess()
{
$data = json_decode(file_get_contents('php://input'), true);
Logger::addLog('[ZaloPay][Callback] Trigger callback: ' . json_encode($data));

$key2 = Configuration::get('ZALOPAY_KEY2');

Logger::addLog('[ZaloPay][Callback] Begin processing callback ');

$response = [];
try {
$hmacinput = $data['data'];
$mac = hash_hmac("sha256", $hmacinput, $key2);

$valid = $mac == $data['mac'];
Logger::addLog('[ZaloPay][Callback] Mac is ' . ($valid ? 'VALID' : 'INVALID'));

if ($valid) {
// Payment success
$mailVars = array(
'{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER'),
'{bankwire_details}' => nl2br(Configuration::get('BANK_WIRE_DETAILS')),
'{bankwire_address}' => nl2br(Configuration::get('BANK_WIRE_ADDRESS'))
);

$embed_data = json_decode(json_decode($data['data'], true)['embed_data'], true);

Logger::addLog('[ZaloPay][Callback] Validating order: ' . json_encode($embed_data));
$this->module->validateOrder(
$embed_data['cart_id'],
Configuration::get('PS_OS_PAYMENT'),
$embed_data['total'],
$this->module->displayName,
NULL,
$mailVars,
(int)$embed_data['currency_id'],
false,
$embed_data['secure_key']
);
$response["return_code"] = 1;
$response["return_message"] = "success";
} else {
$response["return_code"] = -1;
$response["return_message"] = "mac not equal";
}
} catch (\Throwable $th) {
$response["return_code"] = 0; // ZaloPay server sẽ callback lại (tối đa 3 lần)
$response["return_message"] = $th->getMessage();
} finally {
Logger::addLog('[ZaloPay][Callback] Callback processed: ' . json_encode($response));
header('Content-Type: application/json');
die(Tools::jsonEncode($response));
}
}
}
87 changes: 87 additions & 0 deletions zalopay/controllers/front/redirect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/

/**
* @since 1.5.0
*/
class ZaloPayRedirectModuleFrontController extends ModuleFrontController
{
/**
* @see FrontController::postProcess()
*/
public function postProcess()
{
Logger::addLog('[ZaloPay][Redirect] Trigger redirect: ' . json_encode($_REQUEST));

$cart = $this->context->cart;
if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
$this->redirectToOrder();
}

// Check that this payment option is still available in case the customer changed his address just before the end of the checkout process
$authorized = false;
foreach (Module::getPaymentModules() as $module) {
if ($module['name'] == 'zalopay') {
$authorized = true;
break;
}
}

if (!$authorized) {
die($this->module->l('This payment method is not available.', 'validation'));
}

if ($_REQUEST["status"] != 1) {
$this->redirectToOrder();
}

$customer = $this->context->customer;
$appid = Configuration::get('ZALOPAY_APPID');
$key2 = Configuration::get('ZALOPAY_KEY2');

$hmacinput = $appid . "|" . $_REQUEST["apptransid"] . "|" . $_REQUEST["pmcid"] . "|" . $_REQUEST["bankcode"] . "|" . $_REQUEST["amount"] . "|" . $_REQUEST["discountamount"] . "|" . $_REQUEST["status"];
$mac = hash_hmac("sha256", $hmacinput, $key2);

$valid = $mac == $_REQUEST["checksum"];

if ($valid) {
// Payment success
$customer = new Customer($cart->id_customer);
if (!Validate::isLoadedObject($customer)) $this->redirectToOrder();
$cart_id = explode("_", $_REQUEST["apptransid"])[1];
$url = $this->context->link->getPageLink('order-confirmation', true, $customer->id_lang, 'key='.$customer->secure_key.'&id_cart='.$cart_id.'&id_module='.(int)$this->module->id);
Logger::addLog('[ZaloPay][Redirect] Redirect to order confirmination: ' . $url);
Tools::redirectLink($url);
} else {
$this->redirectToOrder();
}
}

public function redirectToOrder()
{
Tools::redirect($this->context->link->getPageLink('order', true));
}
}
100 changes: 55 additions & 45 deletions zalopay/controllers/front/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,64 +52,74 @@ public function postProcess()
die($this->module->l('This payment method is not available.', 'validation'));
}

$this->context->smarty->assign([
'params' => $_REQUEST,
'cart' => $cart,
]);

$this->createOrder();

//$this->setTemplate('payment_return.tpl');
$this->setTemplate('module:zalopay/views/templates/front/payment_return.tpl');


// $customer = new Customer($cart->id_customer);
// if (!Validate::isLoadedObject($customer))
// Tools::redirect('index.php?controller=order&step=1');

// $currency = $this->context->currency;
// $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
// $mailVars = array(
// '{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER'),
// '{bankwire_details}' => nl2br(Configuration::get('BANK_WIRE_DETAILS')),
// '{bankwire_address}' => nl2br(Configuration::get('BANK_WIRE_ADDRESS'))
// );

// $this->module->validateOrder($cart->id, Configuration::get('PS_OS_BANKWIRE'), $total, $this->module->displayName, NULL, $mailVars, (int)$currency->id, false, $customer->secure_key);
// Tools::redirect('index.php?controller=order-confirmation&id_cart='.$cart->id.'&id_module='.$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
$order = $this->createOrder();
print_r($order);

if ($order['return_code'] == 1) {
$url = $order['order_url'];
Tools::redirect($url);
} else {
$this->context->smarty->assign([
'result' => $order,
]);
Tools::redirect('index.php?controller=order&step=1');
}
}

public function createOrder()
{
$cart = $this->context->cart;
$customer = $this->context->customer;

$appid = "553";
$key1 = "9phuAOYhan4urywHTh0ndEXiV3pKHr5Q";
$createOrderUrl = "https://sandbox.zalopay.com.vn/v001/tpe/createorder";
$appid = Configuration::get('ZALOPAY_APPID');
$key1 = Configuration::get('ZALOPAY_KEY1');

$createOrderUrl = "https://sb-openapi.zalopay.vn/v2/create";
$item = array_map(function ($product) {
return [
'id' => $product['id_product'],
'name' => $product['name'],
'quantity' => $product['cart_quantity'],
'price' => $product['price']
];
}, $cart->getProducts());
$title = implode(", ", array_column($item, 'name'));
$callback = $this->context->link->getModuleLink($this->module->name, 'callback', array(), true);
$redirect = $this->context->link->getModuleLink($this->module->name, 'redirect', array(), true);
$currency = $this->context->currency;
$total = (float)$cart->getOrderTotal(true, Cart::BOTH);

$payload = [
"appid" => $appid,
"appuser" => $customer->email,
"apptime" => time(),
"amount" => $cart->getOrderTotal(),
"apptransid" => date("ymd") . '_' . $cart->id,
"embeddata" => "",
"item" => json_encode($cart->getProducts()),
"bankcode" => "",
"description" => sprintf("Thanh toán đơn hàng của %s %s - donghophattai.com", $customer->id_gender == 1 ? "anh" : "chị", $customer->firstname),
"app_id" => $appid,
"app_user" => $customer->email,
"app_time" => round(microtime(true) * 1000),
"amount" => $total,
"app_trans_id" => date("ymd") . time() . '_' . $cart->id,
"callback_url" => $callback,
"order_type" => "GOODS",
"embed_data" => json_encode([
'redirecturl' => $redirect,
'cart_id' => $cart->id,
'total' => $total,
'currency_id' => $currency->id,
'secure_key' => $customer->secure_key
]),
"item" => json_encode($item),
"bank_code" => "",
"title" => $title,
"description" => sprintf("Đồng Hồ Phát Tài - Thanh toán đơn hàng của %s %s", $customer->id_gender == 1 ? "anh" : "chị", $customer->firstname),
"email" => $customer->email,
];
Logger::addLog('[ZaloPay] Send payload: ' . json_encode($payload));

$hmacinput = $appid . "|" . $payload["apptransid"] . "|" . $payload["appuser"] . "|" . $payload["amount"] . "|" . $payload["apptime"] . "|" . $payload["embeddata"] . "|" . $payload["item"];
$hmacinput = $appid . "|" . $payload["app_trans_id"] . "|" . $payload["app_user"] . "|" . $payload["amount"] . "|" . $payload["app_time"] . "|" . $payload["embed_data"] . "|" . $payload["item"];
$mac = hash_hmac("sha256", $hmacinput, $key1);
$payload["mac"] = $mac;

$result = $this->callAPI("POST", $createOrderUrl, $payload);
Logger::addLog('[ZaloPay] Received result: ' . json_encode($result));

printf("<pre>");
print_r($result);
printf("</pre>");
return $result;
}

public function callAPI($method, $url, $data = false)
Expand All @@ -132,16 +142,16 @@ public function callAPI($method, $url, $data = false)
}

// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);

curl_close($curl);

return $result;
if (!$result) {
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
return json_decode($result, true);
}
}
62 changes: 0 additions & 62 deletions zalopay/views/templates/front/payment_form.tpl

This file was deleted.

14 changes: 0 additions & 14 deletions zalopay/views/templates/front/payment_return.tpl

This file was deleted.

Loading

0 comments on commit 294fbbf

Please sign in to comment.