-
Notifications
You must be signed in to change notification settings - Fork 11
/
CardGateExtended.php
230 lines (207 loc) · 8.02 KB
/
CardGateExtended.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php
namespace Tpay\Example\TransactionsApi;
use Tpay\Example\ExamplesConfig;
use Tpay\OpenApi\Api\TpayApi;
use Tpay\OpenApi\Forms\PaymentForms;
use Tpay\OpenApi\Model\Fields\FieldTypes;
use Tpay\OpenApi\Utilities\Logger;
use Tpay\OpenApi\Utilities\TpayException;
use Tpay\OpenApi\Utilities\Util;
final class CardGateExtended extends ExamplesConfig
{
private $TpayApi;
public function __construct()
{
parent::__construct();
$this->TpayApi = new TpayApi(self::MERCHANT_CLIENT_ID, self::MERCHANT_CLIENT_SECRET, true, 'read');
}
public function init()
{
if (isset($_POST['carddata'])) {
$this->processNewCardPayment();
} elseif (isset($_POST['savedId'])) {
// Payment by saved card
$this->processSavedCardPayment($_POST['savedId']);
} else {
$userCards = $this->getUserSavedCards($this->getCurrentUserId());
// Show new payment form
echo (new PaymentForms('en'))
->getOnSiteCardForm(self::MERCHANT_RSA_KEY, 'CardGateExtended.php', true, false, $userCards);
}
}
private function processNewCardPayment()
{
if (isset($_POST['card_vendor'], $_POST['card_short_code'])) {
$this->saveUserCardDetails($_POST['card_vendor'], $_POST['card_short_code']);
}
$transaction = $this->getNewCardTransaction();
if (!isset($transaction['transactionId'])) {
// Code error handling @see POST /transactions HTTP 400 response details
throw new TpayException('Unable to create transaction. Response: '.json_encode($transaction));
}
// Try to sale with provided card data
$response = $this->makeCardPayment($transaction);
if (!isset($response['result']) || 'failure' === $response['result']) {
header('Location: '.$transaction['transactionPaymentUrl']);
}
if (isset($response['status']) && 'correct' === $response['status']) {
// Successful payment by card not protected by 3DS
$this->setOrderAsComplete($response);
} elseif (isset($response['transactionPaymentUrl'])) {
// Successfully generated 3DS link for payment authorization
header('Location: '.$response['transactionPaymentUrl']);
} else {
// Invalid credit card data
header('Location: '.$transaction['transactionPaymentUrl']);
}
}
private function saveUserCardDetails($cardVendor, $cardShortCode)
{
// Code saving the user card vendor name and short code for later use
}
private function getNewCardTransaction()
{
// If you set the fourth getOnSiteCardForm() parameter true, you can get client name and email here. Otherwise, you must get those values from your DB.
$clientEmail = '[email protected]';
$clientName = 'John Doe';
$request = [
'amount' => 0.10,
'description' => 'test transaction',
'hiddenDescription' => 'order_213',
'payer' => [
'email' => $clientEmail,
'name' => $clientName,
],
'lang' => 'pl',
'callbacks' => [
'notification' => [
'url' => 'https://example.com/notification',
],
'payerUrls' => [
'success' => 'https://example.com/success',
'error' => 'https://example.com/error',
],
],
'pay' => [
'groupId' => 103,
],
];
$result = $this->TpayApi->transactions()->createTransaction($request);
if (!isset($result['transactionId'])) {
throw new TpayException('Unable to create transaction. Response: '.json_encode($result));
}
return $result;
}
private function makeCardPayment($transaction)
{
if (isset($_POST['card_save'])) {
$saveCard = Util::cast($_POST['card_save'], FieldTypes::STRING);
} else {
$saveCard = false;
}
$cardData = Util::cast($_POST['carddata'], FieldTypes::STRING);
$request = [
'groupId' => 103,
'cardPaymentData' => [
'card' => $cardData,
'save' => 'on' === $saveCard,
],
'method' => 'pay_by_link',
];
return $this->TpayApi->transactions()->createPaymentByTransactionId($request, $transaction['transactionId']);
}
private function processSavedCardPayment($savedCardId)
{
$transaction = $this->getNewCardTransaction();
$exampleCurrentUserId = $this->getCurrentUserId();
if (!is_numeric($savedCardId)) {
Logger::log('Invalid saved cardId', 'CardId: '.$savedCardId);
return header('Location: '.$transaction['transactionPaymentUrl']);
}
$requestedCardId = (int) $savedCardId;
$currentUserCards = $this->getUserSavedCards($exampleCurrentUserId);
$isValid = false;
$cardToken = '';
foreach ($currentUserCards as $card) {
if ($card['cardId'] === $requestedCardId) {
$isValid = true;
$cardToken = $card['cli_auth'];
}
}
if (false === $isValid) {
Logger::log(
'Unauthorized payment try',
sprintf('User %s has tried to pay by not owned cardId: %s', $exampleCurrentUserId, $requestedCardId)
);
// Reject current payment try and redirect user to tpay payment panel new card form
return header('Location: '.$transaction['transactionPaymentUrl']);
}
return $this->payBySavedCard($cardToken, $transaction);
}
private function payBySavedCard($cardToken, $transaction)
{
$request = [
'groupId' => 103,
'cardPaymentData' => [
'token' => $cardToken,
],
'method' => 'sale',
];
$result = $this->TpayApi->transactions()->createPaymentByTransactionId($request, $transaction['transactionId']);
if (isset($result['result'], $result['status']) && 'success' === $result['status'] && isset($result['payments']['status']) && 'correct' === $result['payments']['status']) {
return $this->setOrderAsComplete($result);
}
return header('Location: '.$transaction['transactionPaymentUrl']);
}
private function setOrderAsComplete($params)
{
// Code setting the order status and other details in your system
var_dump($params);
}
/**
* Returns stored cards by userId as array. Each row contains card details
*
* @param int $userId
*
* @return array
*/
private function getUserSavedCards($userId = 0)
{
// Code getting current logged user cards from your DB. This is only an example of DB.
$exampleDbUsersIdsWithCards = [
0 => [],
2 => [
[
'cardId' => 1,
'vendor' => 'visa',
'shortCode' => '****1111',
'cli_auth' => 't5ca63654a3c44a8fac1dea7f1227b9f5d8dc4af',
],
[
'cardId' => 2,
'vendor' => 'mastercard',
'shortCode' => '****4444',
'cli_auth' => 't5ca636697eebe24b5c2cf02f5d7723f1297f825',
],
],
3 => [
[
'cardId' => 3,
'vendor' => 'visa',
'shortCode' => '****3321',
'cli_auth' => 't5ca6367039f480aa9df557798b47748681f1f05',
],
],
];
if (isset($exampleDbUsersIdsWithCards[$userId])) {
return $exampleDbUsersIdsWithCards[$userId];
}
return [];
}
private function getCurrentUserId()
{
// Code getting the user Id from your system. This is only an example.
return 2;
}
}
(new CardGateExtended())->init();