/
UddoktaPay.php
332 lines (276 loc) · 11.1 KB
/
UddoktaPay.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<?php
/**
* UuddoktaPay FOSSBilling Gateway Module
*
* Copyright (c) 2021 - 2023 UuddoktaPay
* Website: https://uddoktapay.com
* Email: info@uddoktapay.com
* Developer: UddoktaPay Team
*
*/
class Payment_Adapter_UddoktaPay extends Payment_AdapterAbstract implements \FOSSBilling\InjectionAwareInterface
{
private $config = [];
protected ?\Pimple\Container $di;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function __construct($config)
{
$this->config = $config;
if (!isset($this->config['api_key'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'UddoktaPay', ':missing' => 'API KEY']);
}
if (!isset($this->config['api_url'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'UddoktaPay', ':missing' => 'API URL']);
}
if (!isset($this->config['exchange_rate'])) {
throw new Payment_Exception('The ":pay_gateway" payment gateway is not fully configured. Please configure the :missing', [':pay_gateway' => 'UddoktaPay', ':missing' => 'USD to BDT exchange rate [1 USD = ? BDT]']);
}
}
public static function getConfig()
{
return [
'supports_one_time_payments' => true,
'description' => 'Simplify Your Payment Management with UddoktaPay',
'logo' => [
'logo' => 'UddoktaPay/UddoktaPay.png',
'height' => '50px',
'width' => '50px',
],
'form' => [
'api_key' => [
'text', [
'label' => 'API key:',
],
],
'api_url' => [
'text', [
'label' => 'API URL (V2):',
],
],
'exchange_rate' => [
'text', [
'label' => 'USD to BDT exchange rate [1 USD = ? BDT]:',
],
]
],
];
}
public function getHtml($api_admin, $invoice_id, $subscription)
{
$invoice = $api_admin->invoice_get(['id' => $invoice_id]);
$data = $this->upGetPaymentFields($invoice);
$url = $this->upInitPayment($data);
return $this->upGenerateForm($url);
}
public function processTransaction($api_admin, $id, $data, $gateway_id)
{
if (!$this->upIsIpnValid($data)) {
throw new Payment_Exception('Invalid Request');
}
$response = $this->upVerifyPayment($data);
if (isset($response['status']) && $response['status'] == 'COMPLETED') {
$invoice = $this->di['db']->getExistingModelById('Invoice', $response['metadata']['invoice_id'], 'Invoice not found');
$transaction = $this->di['db']->getExistingModelById('Transaction', $id, 'Transaction not found');
$amount = $this->upCurrencyConvertForTransaction($response['amount'], $response['metadata']['currency']);
$tx_data = [
'id' => $id,
'invoice_id' => $response['metadata']['invoice_id'],
'txn_status' => $response['status'],
'txn_id' => $response['transaction_id'],
'amount' => $amount,
'currency' => $invoice->currency,
'type' => $response['payment_method'],
'status' => 'complete',
];
$transactionService = $this->di['mod_service']('Invoice', 'Transaction');
$transactionService->update($transaction, $tx_data);
$bd = [
'amount' => $amount,
'description' => $response['payment_method'] . ' Transaction ID: ' . $response['transaction_id'],
'type' => 'transaction',
'rel_id' => $transaction->id,
];
$client = $this->di['db']->getExistingModelById('Client', $invoice->client_id, 'Client not found');
$clientService = $this->di['mod_service']('client');
if ($this->upIsIpnDuplicate($response)) {
throw new Payment_Exception('Cannot process duplicate IPN');
}
$clientService->addFunds($client, $bd['amount'], $bd['description'], $bd);
$invoiceService = $this->di['mod_service']('Invoice');
$invoiceService->payInvoiceWithCredits($invoice);
$invoiceService->doBatchPayWithCredits(['client_id' => $invoice->client_id]);
$this->upDoRredirect($response['metadata']['return_url']);
} else {
throw new Payment_Exception('Invalid Request');
}
}
/**
* Set Payment Fields for UddoktaPay
* @var array $invoice
*/
public function upGetPaymentFields($invoice)
{
$first_name = isset($invoice['client']['first_name']) ? $invoice['client']['first_name'] : "John";
$last_name = isset($invoice['client']['last_name']) ? $invoice['client']['last_name'] : "";
$email = isset($invoice['client']['email']) ? $invoice['client']['email'] : "test@test.com";
$fields = [
'full_name' => $first_name . ' ' . $last_name,
'email' => $email,
'amount' => $this->upCurrencyConvert($invoice['subtotal'], $invoice['currency']),
'metadata' => [
'invoice_id' => $invoice['id'],
'currency' => $invoice['currency'],
'return_url' => $this->config['return_url']
],
'redirect_url' => $this->config['notify_url'],
'return_type' => 'GET',
'cancel_url' => $this->config['cancel_url'],
'webhook_url' => $this->config['notify_url']
];
return $fields;
}
/**
* Generate Payment Form
* @var string $url
* @var string $method
*/
private function upGenerateForm($url, $method = 'get')
{
$form = '';
$form .= '<form name="payment_form" action="' . $url . '" method="' . $method . '">' . PHP_EOL;
$form .= '<input class="bb-button bb-button-submit" type="submit" value="Pay Now" id="payment_button"/>' . PHP_EOL;
$form .= '</form>' . PHP_EOL . PHP_EOL;
if (isset($this->config['auto_redirect']) && $this->config['auto_redirect']) {
$form .= sprintf('<h2>%s</h2>', __trans('Redirecting to Payment Page...'));
$form .= "<script type='text/javascript'>$(document).ready(function(){ document.getElementById('payment_button').style.display = 'none'; document.forms['payment_form'].submit();});</script>";
}
return $form;
}
/**
* Init Payment
* @var array $requestData
*/
private function upInitPayment($requestData)
{
$host = parse_url($this->config['api_url'], PHP_URL_HOST);
$apiUrl = "https://{$host}/api/checkout-v2";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($requestData),
CURLOPT_HTTPHEADER => [
"RT-UDDOKTAPAY-API-KEY: " . $this->config['api_key'],
"accept: application/json",
"content-type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new Payment_Exception("cURL Error #:" . $err);
} else {
$result = json_decode($response, true);
if (isset($result['status']) && isset($result['payment_url'])) {
return $result['payment_url'];
} else {
throw new Payment_Exception($result['message']);
}
}
throw new Payment_Exception("Please recheck configurations");
}
/**
* Verify Payment
* @var array $data
*/
private function upVerifyPayment($data)
{
$raw_data = json_decode($data['http_raw_post_data'], true);
if (empty($raw_data)) {
$raw_data = $data['get'];
}
$invoice_id = $raw_data['invoice_id'];
$host = parse_url($this->config['api_url'], PHP_URL_HOST);
$verifyUrl = "https://{$host}/api/verify-payment";
$invoice_data = [
'invoice_id' => $invoice_id
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $verifyUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($invoice_data),
CURLOPT_HTTPHEADER => [
"RT-UDDOKTAPAY-API-KEY: " . $this->config['api_key'],
"accept: application/json",
"content-type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new Payment_Exception("cURL Error #:" . $err);
} else {
return json_decode($response, true);
}
throw new Payment_Exception("Please recheck configurations");
}
public function upDoRredirect($url)
{
header('Location:' . $url);
exit;
}
private function upIsIpnValid($data)
{
$raw_data = json_decode($data['http_raw_post_data'], true);
return isset($data['get']['invoice_id']) || isset($raw_data['invoice_id']) ? true : false;
}
public function upIsIpnDuplicate($response)
{
$sql = 'SELECT id
FROM transaction
WHERE txn_id = :transaction_id
AND txn_status = :transaction_status
AND type = :transaction_type
AND amount = :transaction_amount
LIMIT 2';
$bindings = [
':transaction_id' => $response['transaction_id'],
':transaction_status' => $response['status'],
':transaction_type' => $response['payment_method'],
':transaction_amount' => $response['amount'],
];
$rows = $this->di['db']->getAll($sql, $bindings);
if (count($rows) > 1) {
return true;
}
return false;
}
public function upCurrencyConvert($amount, $currency = null)
{
if ($currency == 'BDT') {
return $amount;
}
return $amount * $this->config['exchange_rate'];
}
public function upCurrencyConvertForTransaction($amount, $currency = null)
{
if ($currency == 'BDT') {
return $amount;
}
return $amount / $this->config['exchange_rate'];
}
}