forked from payfort/payfort-php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PayfortIntegration.php
570 lines (509 loc) · 20.9 KB
/
PayfortIntegration.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
<?php
/**
* @copyright Copyright PayFort 2012-2016
*
*/
class PayfortIntegration
{
public $gatewayHost = 'https://checkout.payfort.com/';
public $gatewaySandboxHost = 'https://sbcheckout.payfort.com/';
public $language = 'en';
/**
* @var string your Merchant Identifier account (mid)
*/
public $merchantIdentifier = 'MERCHANT_IDENTIFIER';
/**
* @var string your access code
*/
public $accessCode = 'ACCESS_CODE';
/**
* @var string SHA Request passphrase
*/
public $SHARequestPhrase = 'SHA_REQUEST_PASSPHRASE';
/**
* @var string SHA Response passphrase
*/
public $SHAResponsePhrase = 'SHA_RESPONSE_PASSPHRASE';
/**
* @var string SHA Type (Hash Algorith)
* expected Values ("sha1", "sha256", "sha512")
*/
public $SHAType = 'sha256';
/**
* @var string command
* expected Values ("AUTHORIZATION", "PURCHASE")
*/
public $command = 'AUTHORIZATION';
/**
* @var decimal order amount
*/
public $amount = 100;
/**
* @var string order currency
*/
public $currency = 'USD';
/**
* @var string item name
*/
public $itemName = 'Apple iPhone 6s Plus';
/**
* @var string you can change it to your email
*/
public $customerEmail = '[email protected]';
/**
* @var boolean for live account change it to false
*/
public $sandboxMode = true;
/**
* @var string project root folder
* change it if the project is not on root folder.
*/
public $projectUrlPath = '/payfort-php-sdk';
public function __construct()
{
}
public function processRequest($paymentMethod)
{
if ($paymentMethod == 'cc_merchantpage' || $paymentMethod == 'cc_merchantpage2' || $paymentMethod == 'installments_merchantpage') {
$merchantPageData = $this->getMerchantPageData($paymentMethod);
$postData = $merchantPageData['params'];
$gatewayUrl = $merchantPageData['url'];
}
else{
$data = $this->getRedirectionData($paymentMethod);
$postData = $data['params'];
$gatewayUrl = $data['url'];
}
$form = $this->getPaymentForm($gatewayUrl, $postData);
echo json_encode(array('form' => $form, 'url' => $gatewayUrl, 'params' => $postData, 'paymentMethod' => $paymentMethod));
exit;
}
public function getRedirectionData($paymentMethod) {
$merchantReference = $this->generateMerchantReference();
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
if ($paymentMethod == 'sadad') {
$this->currency = 'SAR';
}
$postData = array(
'amount' => $this->convertFortAmount($this->amount, $this->currency),
'currency' => strtoupper($this->currency),
'merchant_identifier' => $this->merchantIdentifier,
'access_code' => $this->accessCode,
'merchant_reference' => $merchantReference,
'customer_email' => '[email protected]',
//'customer_name' => trim($order_info['b_firstname'].' '.$order_info['b_lastname']),
'command' => $this->command,
'language' => $this->language,
'return_url' => $this->getUrl('route.php?r=processResponse'),
);
if ($paymentMethod == 'sadad') {
$postData['payment_option'] = 'SADAD';
}
elseif ($paymentMethod == 'naps') {
$postData['payment_option'] = 'NAPS';
$postData['order_description'] = $this->itemName;
}
elseif ($paymentMethod == 'installments') {
$postData['installments'] = 'STANDALONE';
$postData['command'] = 'PURCHASE';
}
$postData['signature'] = $this->calculateSignature($postData, 'request');
$debugMsg = "Fort Redirect Request Parameters \n".print_r($postData, 1);
$this->log($debugMsg);
return array('url' => $gatewayUrl, 'params' => $postData);
}
public function getMerchantPageData($paymentMethod)
{
$merchantReference = $this->generateMerchantReference();
$returnUrl = $this->getUrl('route.php?r=merchantPageReturn');
if(isset($_GET['3ds']) && $_GET['3ds'] == 'no') {
$returnUrl = $this->getUrl('route.php?r=merchantPageReturn&3ds=no');
}
$iframeParams = array(
'merchant_identifier' => $this->merchantIdentifier,
'access_code' => $this->accessCode,
'merchant_reference' => $merchantReference,
'service_command' => 'TOKENIZATION',
'language' => $this->language,
'return_url' => $returnUrl,
);
if($paymentMethod == 'installments_merchantpage'){
$iframeParams['currency'] = strtoupper($this->currency);
$iframeParams['installments'] = 'STANDALONE';
$iframeParams['amount'] = $this->convertFortAmount($this->amount, $this->currency);
}
$iframeParams['signature'] = $this->calculateSignature($iframeParams, 'request');
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
$debugMsg = "Fort Merchant Page Request Parameters \n".print_r($iframeParams, 1);
$this->log($debugMsg);
return array('url' => $gatewayUrl, 'params' => $iframeParams);
}
public function getPaymentForm($gatewayUrl, $postData)
{
$form = '<form style="display:none" name="payfort_payment_form" id="payfort_payment_form" method="post" action="' . $gatewayUrl . '">';
foreach ($postData as $k => $v) {
$form .= '<input type="hidden" name="' . $k . '" value="' . $v . '">';
}
$form .= '<input type="submit" id="submit">';
return $form;
}
public function processResponse()
{
$fortParams = array_merge($_GET, $_POST);
$debugMsg = "Fort Redirect Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
$reason = '';
$response_code = '';
$success = true;
if(empty($fortParams)) {
$success = false;
$reason = "Invalid Response Parameters";
$debugMsg = $reason;
$this->log($debugMsg);
}
else{
//validate payfort response
$params = $fortParams;
$responseSignature = $fortParams['signature'];
$merchantReference = $params['merchant_reference'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
$calculatedSignature = $this->calculateSignature($params, 'response');
$success = true;
$reason = '';
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
$response_message = $params['response_message'];
$status = $params['status'];
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $response_message;
$debugMsg = $reason;
$this->log($debugMsg);
}
}
}
if(!$success) {
$p = $params;
$p['error_msg'] = $reason;
$return_url = $this->getUrl('error.php?'.http_build_query($p));
}
else{
$return_url = $this->getUrl('success.php?'.http_build_query($params));
}
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $return_url . "'\"></body></html>";
exit;
}
public function processMerchantPageResponse()
{
$fortParams = array_merge($_GET, $_POST);
$debugMsg = "Fort Merchant Page Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
$reason = '';
$response_code = '';
$success = true;
if(empty($fortParams)) {
$success = false;
$reason = "Invalid Response Parameters";
$debugMsg = $reason;
$this->log($debugMsg);
}
else{
//validate payfort response
$params = $fortParams;
$responseSignature = $fortParams['signature'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
unset($params['3ds']);
$merchantReference = $params['merchant_reference'];
$calculatedSignature = $this->calculateSignature($params, 'response');
$success = true;
$reason = '';
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
$response_message = $params['response_message'];
$status = $params['status'];
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $response_message;
$debugMsg = $reason;
$this->log($debugMsg);
}
else {
$success = true;
$host2HostParams = $this->merchantPageNotifyFort($fortParams);
$debugMsg = "Fort Merchant Page Host2Hots Response Parameters \n".print_r($fortParams, 1);
$this->log($debugMsg);
if (!$host2HostParams) {
$success = false;
$reason = 'Invalid response parameters.';
$debugMsg = $reason;
$this->log($debugMsg);
}
else {
$params = $host2HostParams;
$responseSignature = $host2HostParams['signature'];
$merchantReference = $params['merchant_reference'];
unset($params['r']);
unset($params['signature']);
unset($params['integration_type']);
$calculatedSignature = $this->calculateSignature($params, 'response');
if ($responseSignature != $calculatedSignature) {
$success = false;
$reason = 'Invalid signature.';
$debugMsg = sprintf('Invalid Signature. Calculated Signature: %1s, Response Signature: %2s', $responseSignature, $calculatedSignature);
$this->log($debugMsg);
}
else {
$response_code = $params['response_code'];
if ($response_code == '20064' && isset($params['3ds_url'])) {
$success = true;
$debugMsg = 'Redirect to 3DS URL : '.$params['3ds_url'];
$this->log($debugMsg);
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $params['3ds_url'] . "'\"></body></html>";
exit;
//header('location:'.$params['3ds_url']);
}
else {
if (substr($response_code, 2) != '000') {
$success = false;
$reason = $host2HostParams['response_message'];
$debugMsg = $reason;
$this->log($debugMsg);
}
}
}
}
}
}
if(!$success) {
$p = $params;
$p['error_msg'] = $reason;
$return_url = $this->getUrl('error.php?'.http_build_query($p));
}
else{
$return_url = $this->getUrl('success.php?'.http_build_query($params));
}
echo "<html><body onLoad=\"javascript: window.top.location.href='" . $return_url . "'\"></body></html>";
exit;
}
}
public function merchantPageNotifyFort($fortParams)
{
//send host to host
if ($this->sandboxMode) {
$gatewayUrl = $this->gatewaySandboxHost . 'FortAPI/paymentPage';
}
else {
$gatewayUrl = $this->gatewayHost . 'FortAPI/paymentPage';
}
$postData = array(
'merchant_reference' => $fortParams['merchant_reference'],
'access_code' => $this->accessCode,
'command' => $this->command,
'merchant_identifier' => $this->merchantIdentifier,
'customer_ip' => $_SERVER['REMOTE_ADDR'],
'amount' => $this->convertFortAmount($this->amount, $this->currency),
'currency' => strtoupper($this->currency),
'customer_email' => $this->customerEmail,
'customer_name' => 'John Doe',
'token_name' => $fortParams['token_name'],
'language' => $this->language,
'return_url' => $this->getUrl('route.php?r=processResponse'),
);
if(!empty($merchantPageData['paymentMethod']) && $merchantPageData['paymentMethod'] == 'installments_merchantpage'){
$postData['installments'] = 'YES';
$postData['plan_code'] = $fortParams['plan_code'];
$postData['issuer_code'] = $fortParams['issuer_code'];
$postData['command'] = 'PURCHASE';
}
if(isset($fortParams['3ds']) && $fortParams['3ds'] == 'no') {
$postData['check_3ds'] = 'NO';
}
//calculate request signature
$signature = $this->calculateSignature($postData, 'request');
$postData['signature'] = $signature;
$debugMsg = "Fort Host2Host Request Parameters \n".print_r($postData, 1);
$this->log($debugMsg);
if ($this->sandboxMode) {
$gatewayUrl = 'https://sbpaymentservices.payfort.com/FortAPI/paymentApi';
}
else {
$gatewayUrl = 'https://paymentservices.payfort.com/FortAPI/paymentApi';
}
$array_result = $this->callApi($postData, $gatewayUrl);
$debugMsg = "Fort Host2Host Response Parameters \n".print_r($array_result, 1);
$this->log($debugMsg);
return $array_result;
}
/**
* Send host to host request to the Fort
* @param array $postData
* @param string $gatewayUrl
* @return mixed
*/
public function callApi($postData, $gatewayUrl)
{
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
$useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0";
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=UTF-8',
//'Accept: application/json, application/*+json',
//'Connection:keep-alive'
));
curl_setopt($ch, CURLOPT_URL, $gatewayUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_ENCODING, "compress, gzip");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); // The number of seconds to wait while trying to connect
//curl_setopt($ch, CURLOPT_TIMEOUT, Yii::app()->params['apiCallTimeout']); // timeout in seconds
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
//$response_data = array();
//parse_str($response, $response_data);
curl_close($ch);
$array_result = json_decode($response, true);
if (!$response || empty($array_result)) {
return false;
}
return $array_result;
}
/**
* calculate fort signature
* @param array $arrData
* @param string $signType request or response
* @return string fort signature
*/
public function calculateSignature($arrData, $signType = 'request')
{
$shaString = '';
ksort($arrData);
foreach ($arrData as $k => $v) {
$shaString .= "$k=$v";
}
if ($signType == 'request') {
$shaString = $this->SHARequestPhrase . $shaString . $this->SHARequestPhrase;
}
else {
$shaString = $this->SHAResponsePhrase . $shaString . $this->SHAResponsePhrase;
}
$signature = hash($this->SHAType, $shaString);
return $signature;
}
/**
* Convert Amount with dicemal points
* @param decimal $amount
* @param string $currencyCode
* @return decimal
*/
public function convertFortAmount($amount, $currencyCode)
{
$new_amount = 0;
$total = $amount;
$decimalPoints = $this->getCurrencyDecimalPoints($currencyCode);
$new_amount = round($total, $decimalPoints) * (pow(10, $decimalPoints));
return $new_amount;
}
public function castAmountFromFort($amount, $currencyCode)
{
$decimalPoints = $this->getCurrencyDecimalPoints($currencyCode);
//return $amount / (pow(10, $decimalPoints));
$new_amount = round($amount, $decimalPoints) / (pow(10, $decimalPoints));
return $new_amount;
}
/**
*
* @param string $currency
* @param integer
*/
public function getCurrencyDecimalPoints($currency)
{
$decimalPoint = 2;
$arrCurrencies = array(
'JOD' => 3,
'KWD' => 3,
'OMR' => 3,
'TND' => 3,
'BHD' => 3,
'LYD' => 3,
'IQD' => 3,
);
if (isset($arrCurrencies[$currency])) {
$decimalPoint = $arrCurrencies[$currency];
}
return $decimalPoint;
}
public function getUrl($path)
{
$url = 'http://' . $_SERVER['HTTP_HOST'] . $this->projectUrlPath .'/'. $path;
return $url;
}
public function generateMerchantReference()
{
return rand(0, 9999999999);
}
/**
* Log the error on the disk
*/
public function log($messages) {
$messages = "========================================================\n\n".$messages."\n\n";
$file = __DIR__.'/trace.log';
if (filesize($file) > 907200) {
$fp = fopen($file, "r+");
ftruncate($fp, 0);
fclose($fp);
}
$myfile = fopen($file, "a+");
fwrite($myfile, $messages);
fclose($myfile);
}
/**
*
* @param type $po payment option
* @return string payment option name
*/
function getPaymentOptionName($po) {
switch($po) {
case 'creditcard' : return 'Credit Cards';
case 'cc_merchantpage' : return 'Credit Cards (Merchant Page)';
case 'installments_merchantpage' : return 'Installments (Merchant Page)';
case 'installments' : return 'Installments';
case 'sadad' : return 'SADAD';
case 'naps' : return 'NAPS';
default : return '';
}
}
}
?>