Skip to content

Commit

Permalink
New code for payment terminals
Browse files Browse the repository at this point in the history
  • Loading branch information
Joao Martins committed Jul 10, 2024
1 parent ed95202 commit c50bf25
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 214 deletions.
2 changes: 1 addition & 1 deletion samples/php8/ecom-server/public/checkout_payment.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
$request = new PaymentInitiationRequest();
$request->setStoreId($config['store_id']);
$request->setPaymentReference($paymentReference);
$request->setAmount($_POST['amount']*100);
$request->setAmount($_POST['amount']);
$request->setCurrency($_POST['currency']);
$request->setOrderId($_POST['order_id']);
$request->setReturnUrl($config['redirect_url'].'?order_id=$orderId');
Expand Down
2 changes: 1 addition & 1 deletion samples/php8/ecom-server/public/terminal_payment_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function generateRandomOrderId($length = 8) {
<input type="number" id="amount" name="amount" value="<?php echo $randomAmount; ?>" required>

<label for="currency">Currency:</label>
<input type="text" id="currency" name="currency" value="GBP" class="readonly" readonly>
<input type="text" id="currency" name="currency" value="<?php echo $config['currency']; ?>" class="readonly" readonly>

<label for="order_id">Order ID:</label>
<input type="text" id="order_id" name="order_id" value="<?php echo $randomOrderId; ?>" required>
Expand Down
42 changes: 26 additions & 16 deletions samples/php8/ecom-server/public/terminal_payment_status_check.php
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
<?php

namespace KodyPayTerminalDemo;

require __DIR__ . '/../vendor/autoload.php';
$config = require __DIR__ . '/config.php';

use KodyPayTerminalDemo\KodyTerminalClient;
use Com\Kodypay\Grpc\Pay\V1\KodyPayTerminalServiceClient;
use Com\Kodypay\Grpc\Pay\V1\PaymentDetailsRequest;
use Grpc\ChannelCredentials;

if (isset($_GET['order_id'])) {
$orderId = $_GET['order_id'];

$client = new KodyTerminalClient();
$paymentDetails = $client->getDetails($orderId);

echo json_encode([
'status' => $paymentDetails->getStatus(),
'order_id' => $paymentDetails->getOrderId(),
'date_created' => $paymentDetails->getDateCreated(),
'date_paid' => $paymentDetails->getDatePaid(),
'failure_reason' => $paymentDetails->getFailureReason(),
'ext_payment_ref' => $paymentDetails->getExtPaymentRef(),
'receipt_json' => $paymentDetails->getReceiptJson(),
]);
$client = new KodyPayTerminalServiceClient($config['hostname'], ['credentials' => ChannelCredentials::createSsl()]);
$metadata = ['X-API-Key' => [$config['api_key']]];

$request = new PaymentDetailsRequest();
$request->setStoreId($config['store_id']);
$request->setOrderId($orderId);

list($response, $status) = $client->PaymentDetails($request, $metadata)->wait();

$status = $response->getStatus();
$data = [
'status' => $status,
'orderId' => $response->getOrderId(),
'dateCreated' => $response->getDateCreated()->serializeToJsonString(),
'datePaid' => $response->getDatePaid() ? $response->getDatePaid()->serializeToJsonString() : null,
'failureReason' => $response->getFailureReason(),
'extPaymentRef' => $response->getExtPaymentRef(),
'receiptJson' => $response->getReceiptJson()
];

echo json_encode($data);
} else {
echo json_encode(['status' => 'ERROR', 'message' => 'Invalid request.']);
echo json_encode(['error' => 'Invalid request']);
}
98 changes: 64 additions & 34 deletions samples/php8/ecom-server/public/terminal_submit_payment.php
Original file line number Diff line number Diff line change
@@ -1,59 +1,89 @@
<?php

namespace KodyPayTerminalDemo;
session_start();

require __DIR__ . '/config.php';
require __DIR__ . '/../vendor/autoload.php';
$config = require __DIR__ . '/config.php';

use Com\Kodypay\Grpc\Pay\V1\KodyPayTerminalServiceClient;
use Com\Kodypay\Grpc\Pay\V1\PaymentStatus;
use Com\Kodypay\Grpc\Pay\V1\PayRequest;
use Grpc\ChannelCredentials;
use Grpc\Metadata;

error_log("Processing terminal payment");

// Check if form is submitted with required parameters
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'], $_POST['tid'])) {
$amount = (float) $_POST['amount'];
$terminalId = $_POST['tid'];
if ($_SERVER['REQUEST_METHOD'] === 'POST' &&
isset($_POST['amount'], $_POST['order_id'], $_POST['terminal_id'], $_POST['currency'])) {

$client = new KodyTerminalClient();
$amount = (float)$_POST['amount'];

$client = new KodyPayTerminalServiceClient($config['hostname'], ['credentials' => ChannelCredentials::createSsl()]);
$metadata = ['X-API-Key' => [$config['api_key']]];

// Sending initial payment request
$response = $client->sendPayment($amount, $terminalId, function ($orderId) {
$_SESSION['current_order_id'] = $orderId;
});
$req = new PayRequest();
$req->setStoreId($config['store_id']);
$req->setAmount(number_format($amount, 2, '.', ''));
$req->setTerminalId($_POST['terminal_id']);

error_log("Sending request");
$timeoutDateTime = (new DateTime())->add(new DateInterval('PT' . (3 * 60) . 'S'));
$call = $client->Pay($req, $metadata, ['timeout' => $timeoutDateTime]);

$orderId = $_SESSION['current_order_id'] ?? null;
error_log("Request submitted");

// Capture the orderId from the callback
$orderId = null;
foreach ($call->responses() as $reply) {
if ($reply->getStatus() === PaymentStatus::PENDING) {
$orderId = $reply->getOrderId();
$_SESSION['current_order_id'] = $orderId;
break;
}
}

if ($orderId) {
echo "<h2>Collecting payment for Order ID: $orderId</h2>";
echo "<div id='loading'>Loading... <img src='spinner.gif' alt='loading spinner'></div>";
echo "<div id='payment-result' style='display:none;'></div>";
} else {
error_log("Error: Unable to initiate payment.");
echo "<h2>Error: Unable to initiate payment.</h2>";
}
} else {
error_log("Error: Invalid request. Form parameters are missing.");
echo "<h2>Error: Invalid request.</h2>";
}
?>

<script>
let orderId = "<?php echo $orderId; ?>";

function checkPaymentStatus() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'terminal_payment_status_check.php?order_id=' + orderId, true);
xhr.onload = function() {
if (xhr.status === 200) {
let response = JSON.parse(xhr.responseText);
if (response.status === 'PENDING') {
setTimeout(checkPaymentStatus, 1000);
<?php if (isset($orderId)): ?>
<script>
let orderId = "<?php echo $orderId; ?>";

function checkPaymentStatus() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'terminal_payment_status_check.php?order_id=' + orderId, true);
xhr.onload = function () {
if (xhr.status === 200) {
let response = JSON.parse(xhr.responseText);
if (response.status === 0) {
setTimeout(checkPaymentStatus, 1000);
} else {
document.getElementById('loading').style.display = 'none';
let resultDiv = document.getElementById('payment-result');
resultDiv.style.display = 'block';
resultDiv.innerHTML = `<h2>Payment Status: ${response.status}</h2><pre>${JSON.stringify(response, null, 2)}</pre>
<a href="terminal_payment_form.php">New payment</a> | <a href="terminals.php">Terminals list</a>`;
}
} else {
document.getElementById('loading').style.display = 'none';
let resultDiv = document.getElementById('payment-result');
resultDiv.style.display = 'block';
resultDiv.innerHTML = `<h2>Payment Status: ${response.status}</h2><pre>${JSON.stringify(response, null, 2)}</pre>
<a href="index.php">Start Again</a> | <a href="checkout.php">Go to Form</a>`;
console.error('Error checking payment status:', xhr.statusText);
}
} else {
console.error('Error checking payment status:', xhr.statusText);
}
};
xhr.send();
}
};
xhr.send();
}

setTimeout(checkPaymentStatus, 1000);
</script>
setTimeout(checkPaymentStatus, 1000);
</script>
<?php endif; ?>
21 changes: 0 additions & 21 deletions samples/php8/pos/src/config.php

This file was deleted.

141 changes: 0 additions & 141 deletions samples/php8/pos/src/demo_payment.php

This file was deleted.

0 comments on commit c50bf25

Please sign in to comment.