Skip to content

Commit

Permalink
Tool - Timeout optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
yidas committed Oct 7, 2019
1 parent 13cc960 commit db7881f
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 58 deletions.
24 changes: 24 additions & 0 deletions README-zh_TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ OUTLINE
- [Capture](#capture)
- [Refund](#refund)
- [取得查看授權記錄 API](#取得查看授權記錄-api)
- [Exceptions](#exceptions)
- [ConnectException](#connectException)
- [外部資源](#外部資源)
- [參考](#參考)

Expand Down Expand Up @@ -537,6 +539,28 @@ $response = $linePay->authorizations([

---

EXCEPTIONS
==========

Client會在API串接處理期間發生錯誤時拋出異常。

### ConnectException

`yidas\linePay\exception\ConnectException` 當出現網路錯誤(如Timeout)時會拋出異常。

```php
try {

$response = $linePay->confirm($transactionId, $bodyParams);

} catch (\yidas\linePay\exception\ConnectException $e) {

// Process of confirm API timeout handling
}
```

---

外部資源
=========

Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ OUTLINE
- [Capture](#capture)
- [Refund](#refund)
- [Authorization Details](#authorization-details)
- [Exceptions](#exceptions)
- [ConnectException](#connectException)
- [Resources](#resources)
- [References](#references)

Expand Down Expand Up @@ -543,6 +545,29 @@ $response = $linePay->authorizations([

---

EXCEPTIONS
==========

Client throws exceptions for errors that occur during a API transaction.

### ConnectException

A `yidas\linePay\exception\ConnectException` exception is thrown in the event of a networking error (Timeout).

```php
try {

$response = $linePay->confirm($transactionId, $bodyParams);

} catch (\yidas\linePay\exception\ConnectException $e) {

// Process of confirm API timeout handling
}

```

---

RESOURCES
=========

Expand Down
54 changes: 48 additions & 6 deletions tool/_config.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
* Save log into logs in session
*
* @param string $name
* @param array $requestBody
* @param string $requestTime
* @param array $responseBody
* @param string $responseTime
* @param \yidas\linePay\Response $response
* @param boolean $reset
* @return void
*/
Expand All @@ -41,11 +38,45 @@ function saveLog($name, \yidas\linePay\Response $response, $reset=false)
'transferTime' => $stats->getTransferTime(),
'request' => [
'content' => ($requestContentArray) ? json_encode($requestContentArray, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) : '',
'datetime' => DateTime::createFromFormat('U.u', $stats->requestTime)->format("Y-m-d H:i:s.u"),
'datetime' => printDateTime($stats->requestTime),
],
'response' => [
'content' => ($responseContentArray) ? json_encode($responseContentArray, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) : '',
'datetime' => DateTime::createFromFormat('U.u', $stats->responseTime)->format("Y-m-d H:i:s.u"),
'datetime' => printDateTime($stats->responseTime),
],
];
$_SESSION['logs'] = $logs;
}

/**
* Save log into logs in session
*
* @param string $name
* @param \Psr\Http\Message\RequestInterface $request
* @param boolean $reset
* @return void
*/
function saveErrorLog($name, \Psr\Http\Message\RequestInterface $request, $reset=false)
{
// Content
$requestContentArray = json_decode($request->getBody());
// Timestamp trick
$request->timestamp = isset($request->timestamp) ? $request->timestamp : time();
// Log
$logs = ($reset) ? [] : $_SESSION['logs'];
$logs[] = [
'name' => $name,
'datetime' => date("c"),
'uri' => urldecode($request->getUri()),
'method' => $request->getMethod(),
'transferTime' => (float) (microtime(true) - $request->timestamp),
'request' => [
'content' => ($requestContentArray) ? json_encode($requestContentArray, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) : '',
'datetime' => printDateTime($request->timestamp),
],
'response' => [
'content' => '',
'datetime' => 'Timeout',
],
];
$_SESSION['logs'] = $logs;
Expand Down Expand Up @@ -95,3 +126,14 @@ public static function getMerchant($key)
return isset($merchants[$key]) ? $merchants[$key] : null;
}
}

/**
* Print formatted date time
*
* @param float $timestamp
* @return string
*/
function printDateTime($timestamp)
{
return DateTime::createFromFormat('U.u', $timestamp)->setTimeZone(new DateTimeZone(date_default_timezone_get()))->format("Y-m-d H:i:s.u");
}
77 changes: 47 additions & 30 deletions tool/confirm.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<?php

use yidas\linePay\Client;
use yidas\linePay\exception\ConnectException;

require __DIR__ . '/_config.php';

// Get saved config
Expand All @@ -8,7 +11,7 @@
die("<script>alert('Session invalid');location.href='./index.php';</script>");
}
// Create LINE Pay client
$linePay = new \yidas\linePay\Client([
$linePay = new Client([
'channelId' => $config['channelId'],
'channelSecret' => $config['channelSecret'],
'isSandbox' => ($config['isSandbox']) ? true : false,
Expand All @@ -31,46 +34,60 @@
'amount' => (integer) $order['params']['amount'],
'currency' => $order['params']['currency'],
];
$response = $linePay->confirm($order['transactionId'], $bodyParams);

// Log
saveLog('Confirm API', $response);

// Save error info if confirm fails
if (!$response->isSuccessful()) {
$_SESSION['linePayOrder']['confirmCode'] = $response['returnCode'];
$_SESSION['linePayOrder']['confirmMessage'] = $response['returnMessage'];
}

// Pre-approved
if (isset($config['preapproved'])) {
$regKey = isset($response['info']['regKey']) ? $response['info']['regKey'] : null;
if (!$regKey) {
die("<script>alert('`regKey` not found!;location.href='{$successUrl}';</script>");
}
$_SESSION['config']['regKey'] = $regKey;
}

// Zero amount for Preapproved (Only Preapproved allows empty amount)
if ($order['params']['amount']!=0) {
// Use Details API to confirm the transaction (Details API verification is more stable then Confirm API)
$response = $linePay->details([
'transactionId' => $order['transactionId'],
]);
// 1st confirm request
try {

$response = $linePay->confirm($order['transactionId'], $bodyParams);

// Log
saveLog('Payment Details API', $response);
saveLog('Confirm API', $response);

// Save error info if confirm fails
if (!$response->isSuccessful()) {
$_SESSION['linePayOrder']['isSuccessful'] = false;
$_SESSION['linePayOrder']['confirmCode'] = $response['returnCode'];
$_SESSION['linePayOrder']['confirmMessage'] = $response['returnMessage'];
die("<script>alert('Confirm Failed\\nErrorCode: {$response['returnCode']}\\nErrorMessage: {$response['returnMessage']}');location.href='{$successUrl}';</script>");
}

// Pre-approved
if (isset($config['preapproved'])) {
$regKey = isset($response['info']['regKey']) ? $response['info']['regKey'] : null;
if (!$regKey) {
die("<script>alert('`regKey` not found!;location.href='{$successUrl}';</script>");
}
$_SESSION['config']['regKey'] = $regKey;
}

// Check the transaction
if (!isset($response["info"]) || $response["info"][0]['transactionId'] != $transactionId) {
} catch (ConnectException $e) {

// Log
saveErrorLog('Confirm API', $linePay->getRequest());

// 2st check Details request
try {

// Retry check by using Details API to confirm the transaction
$response = $linePay->details([
'transactionId' => $order['transactionId'],
]);

} catch (ConnectException $e) {

saveErrorLog('Details API', $linePay->getRequest());
die("<script>alert('APIs has timeout two times, please check transactionId: {$order['transactionId']}');location.href='./';</script>");
}

// Log
saveLog('Details API', $response);

// Check result
if (!$response->isSuccessful() || !isset($response["info"]) || $response["info"][0]['transactionId'] != $transactionId) {
$_SESSION['linePayOrder']['isSuccessful'] = false;
die("<script>alert('Details Failed\\nErrorCode: {$_SESSION['linePayOrder']['confirmCode']}\\nErrorMessage: {$_SESSION['linePayOrder']['confirmMessage']}');location.href='{$successUrl}';</script>");
$_SESSION['linePayOrder']['confirmCode'] = $response['returnCode'];
$_SESSION['linePayOrder']['confirmMessage'] = $response['returnMessage'];
die("<script>alert('Details Failed\\nErrorCode: {$response['returnCode']}\\nErrorMessage: {$response['returnMessage']}');location.href='{$successUrl}';</script>");
}
}

Expand Down
7 changes: 5 additions & 2 deletions tool/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,11 @@ function formSubmit(form) {
<hr>
<p><strong>Refund Info</strong></p>
<?php foreach ($order['info']['refundList'] as $key => $refund): ?>
<p>RefundAmount: <?=$refund['refundAmount']?></p>
<p>RefundTransactionDate: <?=$refund['refundTransactionDate']?></p>
<p>
Refund (<?=date('c', strtotime($refund['refundTransactionDate']))?>)<br>
TransactionId: <?=$refund['refundTransactionId']?><br>
Amount: <?=$refund['refundAmount']?>
</p>
<?php endforeach ?>
<?php endif ?>
<?php if(isset($config['captureFalse'])):?>
Expand Down
61 changes: 41 additions & 20 deletions tool/onetimekeys-pay.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<?php

use yidas\linePay\Client;
use yidas\linePay\exception\ConnectException;

require __DIR__ . '/_config.php';

$input = $_POST;
Expand All @@ -13,7 +16,7 @@
}

// Create LINE Pay client
$linePay = new \yidas\linePay\Client([
$linePay = new Client([
'channelId' => $input['channelId'],
'channelSecret' => $input['channelSecret'],
'isSandbox' => $input['isSandbox'],
Expand Down Expand Up @@ -44,15 +47,45 @@
$orderParams['extras']['promotionRestriction']['rewardLimit'] = ($input['rewardLimit']) ? $input['rewardLimit'] : 0;
}

// Online Reserve API
$response = $linePay->oneTimeKeysPay($orderParams);
// 1st Pay request
try {

// Online Reserve API
$response = $linePay->oneTimeKeysPay($orderParams);

// Log
saveLog('OneTimeKeysPay API', $response, true);

// Check Reserve API result
if (!$response->isSuccessful()) {
die("<script>alert('ErrorCode {$response['returnCode']}: {$response['returnMessage']}');history.back();</script>");
}

} catch(ConnectException $e) {

// Log
saveErrorLog('OneTimeKeysPay API', $linePay->getRequest(), true);

// Log
saveLog('OneTimeKeysPay API', $response, true);
// 2st check requst
try {
// Use Order Check API to confirm the transaction
$response = $linePay->ordersCheck($orderId);

// Check Reserve API result
if (!$response->isSuccessful()) {
die("<script>alert('ErrorCode {$response['returnCode']}: {$response['returnMessage']}');history.back();</script>");
} catch (ConnectException $e) {

// Log
saveErrorLog('Payment Status Check API', $linePay->getRequest());
die("<script>alert('APIs has timeout two times, please check orderId: {$orderId}');location.href='./';</script>");
}

// Log
saveLog('Payment Status Check API', $response);

// Check the transaction
if (!$response->isSuccessful() || !isset($response["info"]) || $response["info"]['orderId'] != $orderId) {
$_SESSION['linePayOrder']['isSuccessful'] = false;
die("<script>alert('Payment Status Check Failed\\nErrorCode {$response['returnCode']}: {$response['returnMessage']}');history.back();</script>");
}
}

// Save the order info to session for confirm
Expand All @@ -64,18 +97,6 @@
// Save input for next process and next form
$_SESSION['config'] = $input;

// Use Order Check API to confirm the transaction
$response = $linePay->ordersCheck($orderId);

// Log
saveLog('Payment Status Check API', $response);

// Check the transaction
if (!isset($response["info"]) || $response["info"]['orderId'] != $orderId) {
$_SESSION['linePayOrder']['isSuccessful'] = false;
die("<script>alert('Payment Status Check Failed\\nErrorCode {$response['returnCode']}: {$response['returnMessage']}');history.back();</script>");
}

// Code for saving the successful order into your application database...
$_SESSION['linePayOrder']['isSuccessful'] = true;
$_SESSION['linePayOrder']['info'] = $response["info"];
Expand Down

0 comments on commit db7881f

Please sign in to comment.