Skip to content

Commit

Permalink
sandbox switch and properly log messages
Browse files Browse the repository at this point in the history
  • Loading branch information
mister-teddy committed Jul 25, 2021
1 parent 294fbbf commit bee1545
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 38 deletions.
19 changes: 5 additions & 14 deletions zalopay/controllers/front/callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,22 @@ class ZaloPayCallbackModuleFrontController extends ModuleFrontController
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'))
);
$mailVars = array();

$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'),
Expand All @@ -72,16 +63,16 @@ public function postProcess()
$embed_data['secure_key']
);
$response["return_code"] = 1;
$response["return_message"] = "success";
$response["return_message"] = "MAC hợp lệ, đơn hàng đã được tạo thành công!";
} else {
$response["return_code"] = -1;
$response["return_message"] = "mac not equal";
$response["return_message"] = "MAC không hợp lệ!.";
}
} catch (\Throwable $th) {
$response["return_code"] = 0; // ZaloPay server sẽ callback lại (tối đa 3 lần)
$response["return_message"] = $th->getMessage();
$response["return_message"] = sprintf("Lỗi không xác định - %s", $th->getMessage());
} finally {
Logger::addLog('[ZaloPay][Callback] Callback processed: ' . json_encode($response));
Logger::addLog(sprintf("[ZaloPay][Callback] Xử lý callback %s! Chi tiết: %s.", $response['return_code'] == 1 ? 'thành công' : 'thất bại', $response['return_message']));
header('Content-Type: application/json');
die(Tools::jsonEncode($response));
}
Expand Down
7 changes: 3 additions & 4 deletions zalopay/controllers/front/redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ class ZaloPayRedirectModuleFrontController extends ModuleFrontController
*/
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();
Expand Down Expand Up @@ -72,8 +70,8 @@ public function postProcess()
$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);
$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(sprintf("[ZaloPay][Redirect] Thanh toán %s thành công! Quay về trang xác nhận đơn hàng: %s", $_REQUEST['amount'], $url));
Tools::redirectLink($url);
} else {
$this->redirectToOrder();
Expand All @@ -82,6 +80,7 @@ public function postProcess()

public function redirectToOrder()
{
Logger::addLog(sprintf("[ZaloPay][Redirect] Thanh toán %s thất bại! Mã lỗi: %s. Quay về trang đặt hàng, bước thanh toán.", $_REQUEST['amount'], $_REQUEST['status']));
Tools::redirect($this->context->link->getPageLink('order', true));
}
}
7 changes: 4 additions & 3 deletions zalopay/controllers/front/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,12 @@ public function createOrder()
$cart = $this->context->cart;
$customer = $this->context->customer;

$sandbox = Configuration::get('ZALOPAY_SANDBOX');
$appid = Configuration::get('ZALOPAY_APPID');
$key1 = Configuration::get('ZALOPAY_KEY1');

$createOrderUrl = "https://sb-openapi.zalopay.vn/v2/create";
$createOrderUrl = $sandbox ? "https://sb-openapi.zalopay.vn/v2/create" : "https://openapi.zalopay.vn/v2/create";

$item = array_map(function ($product) {
return [
'id' => $product['id_product'],
Expand Down Expand Up @@ -110,14 +112,13 @@ public function createOrder()
"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["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));
Logger::addLog(sprintf("[ZaloPay][Validation] %s. Mã trả về: %s. Chi tiết %s (%s)", $result['return_message'], $result['return_code'], $result['sub_return_message'], $result['sub_return_code']));

return $result;
}
Expand Down
3 changes: 2 additions & 1 deletion zalopay/views/templates/front/payment_infos.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@
*}

<section>
<p>{l s='Thanh toán trực tuyến qua Cổng ZaloPay' mod='mypaymentmodule'}</p>
<p>{l s='Các hình thức thanh toán được hỗ trợ: Thẻ ATM nội địa/Internet Banking, VISA, MasterCard, JCB và Ví điện tử ZaloPay. Nhấn nút Đặt Hàng để bắt đầu thanh toán!' mod='zalopay'}</p>
<p>Một thẻ cào điện thoại mệnh giá ngẫu nhiên 20k - 100k sẽ được vận chuyển chung với đơn hàng của bạn. Vui lòng để lại số điện thoại để bên mình biết nhà mạng mà bạn đang sử dụng. <b>Không áp dụng chung với gói quà!</b></p>
</section>
47 changes: 31 additions & 16 deletions zalopay/zalopay.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,17 @@ public function __construct()
$this->bootstrap = true;
parent::__construct();

$this->displayName = $this->l('ZaloPay Gateway');
$this->displayName = $this->l('Cổng ZaloPay');
$this->description = $this->l('Thanh toán trực tuyến qua Cổng ZaloPay');

if (!count(Currency::checkPaymentCurrencies($this->id))) {
$this->warning = $this->l('No currency has been set for this module.');
$this->warning = $this->l('Không có đơn vị tiền tệ nào được thiết lập');
}
}

public function install()
{
Configuration::updateValue('ZALOPAY_SANDBOX', true);
if (!parent::install() || !$this->registerHook('paymentOptions') || !$this->registerHook('paymentReturn')) {
return false;
}
Expand Down Expand Up @@ -107,17 +108,9 @@ public function checkCurrency($cart)
public function getExternalPaymentOption()
{
$externalOption = new PaymentOption();
$externalOption->setCallToActionText($this->l('Thanh toán trực tuyến'))
$externalOption->setCallToActionText($this->l('Thanh toán trực tuyến qua cổng thanh toán'))
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
->setInputs([
'token' => [
'name' => 'token',
'type' => 'hidden',
'value' => '12345689',
],
])
->setAdditionalInformation($this->context->smarty->fetch('module:zalopay/views/templates/front/payment_infos.tpl'))
->setLogo(Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/logo.png'));
->setAdditionalInformation($this->context->smarty->fetch('module:zalopay/views/templates/front/payment_infos.tpl'));

return $externalOption;
}
Expand All @@ -126,14 +119,16 @@ public function getContent()
{
$output = null;
if (Tools::isSubmit('submit' . $this->name)) {
$sandbox = $_POST['sandbox'];
$appid = $_POST['appid'];
$key1 = $_POST['key1'];
$key2 = $_POST['key2'];

Configuration::updateValue('ZALOPAY_SANDBOX', $sandbox);
Configuration::updateValue('ZALOPAY_APPID', $appid);
Configuration::updateValue('ZALOPAY_KEY1', $key1);
Configuration::updateValue('ZALOPAY_KEY2', $key2);
$output .= $this->displayConfirmation($this->l('Settings updated'));
$output .= $this->displayConfirmation($this->l('Lưu thay đổi thành công!'));
}
return $output . $this->displayForm();
}
Expand All @@ -146,9 +141,28 @@ public function displayForm()
// Init Fields form array
$fieldsForm[0]['form'] = [
'legend' => [
'title' => $this->l('ZaloPlay Settings'),
'title' => $this->l('Thiết lập ZaloPay'),
],
'input' => [
[
'type' => 'switch',
'label' => $this->l('Chế độ Sandbox'),
'name' => 'sandbox',
'is_bool' => true,
'desc' => $this->l('Bật chế độ Sandbox để test bằng ứng dụng ZaloPay sandbox hoặc thẻ ATM giả để không bị trừ tiền'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
],
[
'type' => 'text',
'label' => $this->l('AppID'),
Expand All @@ -166,7 +180,7 @@ public function displayForm()
]
],
'submit' => [
'title' => $this->l('Save'),
'title' => $this->l('Lưu'),
'class' => 'btn btn-default pull-right'
]
];
Expand Down Expand Up @@ -196,11 +210,12 @@ public function displayForm()
],
'back' => [
'href' => AdminController::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
'desc' => $this->l('Quay về')
]
];

// Load current value
$helper->fields_value['sandbox'] = Configuration::get('ZALOPAY_SANDBOX');
$helper->fields_value['appid'] = Configuration::get('ZALOPAY_APPID');
$helper->fields_value['key1'] = Configuration::get('ZALOPAY_KEY1');
$helper->fields_value['key2'] = Configuration::get('ZALOPAY_KEY2');
Expand Down

0 comments on commit bee1545

Please sign in to comment.