-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPSPInterface.php
More file actions
776 lines (632 loc) · 29.4 KB
/
PSPInterface.php
File metadata and controls
776 lines (632 loc) · 29.4 KB
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
<?php
// ======================================================================================
// Payment Service Provider Interface
// ======================================================================================
/// <container name="PSPI">
/// Interface exposing payment functionality
/// </container>
interface PSPI
{
/// <function container="PSPI" name="RedirectToPaymentForm" access="public">
/// <description> Redirects user to payment form/window </description>
/// <param name="orderId" type="string"> Unique ID identifying payment </param>
/// <param name="amount" type="integer"> Order amount in smallest possible unit (e.g. Cents for USD) </param>
/// <param name="currency" type="string"> Currency in the format defined by ISO 4217 (e.g. USD, GBP, or USD) </param>
/// <param name="continueUrl" type="string"> URL to which user is redirected after completing payment - e.g. a receipt </param>
/// <param name="callbackUrl" type="string">
/// URL called asynchronously when payment is successfully carried through.
/// Use PSP::GetCallbackData() to obtain OrderId, TransactionId, Amount, Currency, and MetaData.
/// </param>
/// </function>
public function RedirectToPaymentForm($orderId, $amount, $currency, $continueUrl = null, $callbackUrl = null);
/// <function container="PSPI" name="CapturePayment" access="public" returns="boolean">
/// <description> Capture payment previously authorized using payment form - returns True on success, otherwise False </description>
/// <param name="transactionId" type="string"> Unique ID identifying transaction </param>
/// <param name="amount" type="integer"> Amount to withdraw in smallest possible unit (e.g. Cents for USD) </param>
/// </function>
public function CapturePayment($transactionId, $amount);
/// <function container="PSPI" name="CancelPayment" access="public" returns="boolean">
/// <description> Cancel payment previously authorized using payment form - returns True on success, otherwise False </description>
/// <param name="transactionId" type="string"> Unique ID identifying transaction </param>
/// </function>
public function CancelPayment($transactionId);
}
// ======================================================================================
// Payment Service Provider Wrapper (PSPW) - wraps PSPM
// ======================================================================================
class PSPW implements PSPI
{
private $pspm = null;
public function __construct(PSPI $pspModule)
{
$this->pspm = $pspModule;
}
public function RedirectToPaymentForm($orderId, $amount, $currency, $continueUrl = null, $callbackUrl = null)
{
if (is_string($orderId) === false || is_integer($amount) === false || is_string($currency) === false || ($continueUrl !== null && is_string($continueUrl) === false) || ($callbackUrl !== null && is_string($callbackUrl) === false))
throw new Exception("Invalid argument(s) passed to RedirectToPaymentForm(string, integer, string[, string[, string]])");
//if (strpos($continueUrl, "?") !== false || strpos($callbackUrl, "?") !== false)
// throw new Exception("Invalid callback URL(s) passed - URL parameters are not allowed");
$this->pspm->RedirectToPaymentForm($orderId, $amount, $currency, $continueUrl, $callbackUrl);
}
public function CapturePayment($transactionId, $amount)
{
if (is_string($transactionId) === false || is_int($amount) === false)
throw new Exception("Invalid argument(s) passed to CapturePayment(string, integer)");
return $this->pspm->CapturePayment($transactionId, $amount);
}
public function CancelPayment($transactionId)
{
if (is_string($transactionId) === false)
throw new Exception("Invalid argument passed to CancelPayment(string)");
return $this->pspm->CancelPayment($transactionId);
}
}
// ======================================================================================
// PSP Helper class
// ======================================================================================
/// <container name="PSP">
/// Class exposing functionality useful to Payment Service Provider Modules
/// </container>
class PSP
{
private static $baseConfig = null;
private static $configurations = array();
private static $currencies = null;
private static $numCurrencies = null;
// Factory
/// <function container="PSP" name="GetPaymentProvider" access="public" static="true" returns="PSPI">
/// <description> Get instance of Payment Service Provider Module which implements the PSPI interface </description>
/// <param name="provider" type="string"> Name of Payment Service Provider Module </param>
/// </function>
public static function GetPaymentProvider($provider)
{
if (is_string($provider) === false)
throw new Exception("Invalid argument passed to GetPaymentProvider(string)");
$path = dirname(__FILE__) . "/" . $provider . "/PSPM.php";
if (is_file($path) === false)
throw new Exception("Unable to load PSPM from '" . $path . "' - not found");
require_once($path);
if (class_exists($provider, false) === false)
throw new Exception("Unable to create instance of PSPM class '" . $provider . "' - not defined");
return new PSPW(new $provider()); // Both PSPM and PSPW implements PSPI interface
}
// Communication
/// <function container="PSP" name="Post" access="public" static="true" returns="string">
/// <description> Post data to given URL </description>
/// <param name="url" type="string"> Target URL </param>
/// <param name="data" type="string[]" default="null"> Associative array contain data as key/value pairs </param>
/// <param name="headers" type="string[]" default="null"> Optional associative array contain headers as key/value pairs </param>
/// </function>
public static function Post($url, $data = null, $headers = null)
{
if (is_string($url) === false)
throw new Exception("Invalid argument(s) passed to Post(string, string[], string[]");
foreach ((($data !== null) ? $data : array()) as $key => $value)
{
if (is_string($key) === false || is_string($value) === false)
throw new Exception("Invalid argument(s) passed to Post(string, string[], string[])");
}
foreach ((($headers !== null) ? $headers : array()) as $key => $value)
{
if (is_string($key) === false || is_string($value) === false)
throw new Exception("Invalid argument(s) passed to Post(string, string[], string[])");
}
// Prepare header(s)
$header = "";
$contentTypeSet = false;
if ($headers !== null)
{
foreach ($headers as $key => $value)
{
if (strtolower($key) === "content-type")
$contentTypeSet = true;
$header .= (($header !== "") ? "\r\n" : "") . $key . ": " . $value;
}
}
if ($contentTypeSet === false) // Avoid error: Content-type not specified assuming application/x-www-form-urlencoded
{
$header .= (($header !== "") ? "\r\n" : "") . "Content-Type: application/x-www-form-urlencoded";
}
// Create stream context
$sc = stream_context_create(
array(
"http" => array(
"method" => "POST",
"header" => $header,
"content" => http_build_query((($data !== null) ? $data : array())),
"ignore_errors" => true // Prevent errors caused by HTTP status codes such as "201 Created" on older versions of PHP (found with PHP 5.2.17 on MAMP Pro) - this will make file_get_contents() return error message (e.g. '404 Not Found') rather than False, but strangely return the actual response for "201 Created" which previously caused an error
)
)
);
// Perform request
$response = file_get_contents($url, false, $sc); // https:// requires openssl to be enabled (http://php.net/manual/en/wrappers.http.php)
if ($response === false)
throw new Exception("Request to URL '" . $url . "' failed");
// Check response (compensate for ignore_errors=true in stream context above)
$statusCode = -1;
$matches = array();
foreach ($http_response_header as $responseHeader) // $http_response_header is "magically" created by PHP when file_get_contents(..) is invoked
{
if (preg_match('/HTTP\/.*? (.*) .*/i', $responseHeader, $matches, PREG_OFFSET_CAPTURE) === 1) // $matches[0][0] = full match, $matches[0][1] = full match position, $matches[1][0] = capture group (status code), $matches[1][1] = capture group position
{
$statusCode = (int)$matches[1][0];
break;
}
}
if ($statusCode < 200 || $statusCode > 299)
{
throw new Exception("Request to URL '" . $url . "' failed - HTTP Status Code: '" . (string)$statusCode . "'");
}
// Return response
return $response; //return array("Headers" => $http_response_header, "Response" => $response);
}
/// <function container="PSP" name="RedirectToContinueUrl" access="public" static="true">
/// <description> Redirect user to Continue URL passed to RedirectToPaymentForm(..) </description>
/// <param name="url" type="string"> Continue URL </param>
/// </function>
public static function RedirectToContinueUrl($url)
{
if (is_string($url) === false)
throw new Exception("Invalid argument passed to RedirectToContinueUrl(string)");
//if (strpos($url, "?") !== false) // Prevent PSPM from appending arguments
//throw new Exception("Invalid Continue URL passed - URL parameters are not allowed");
header("location: " . $url);
exit;
}
/// <function container="PSP" name="InvokeCallback" access="public" static="true" returns="string">
/// <description> Invoke callback - used by PSPM to invoke callbacks passed to RedirectToPaymentForm(..) </description>
/// <param name="callbackUrl" type="string"> Callback URL </param>
/// <param name="transactionId" type="string">
/// Transaction ID used for further processing (e.g. Capture/Cancel).
/// Pass empty string if further processing is not supported.
/// </param>
/// <param name="orderId" type="string"> Order ID </param>
/// <param name="amount" type="integer"> Order amount in smallest possible unit (e.g. Cents for USD) </param>
/// <param name="currency" type="string"> Currency in the format defined by ISO 4217 (e.g. USD, GBP, or USD) </param>
/// <param name="metaData" type="PSPPaymentMetaData" default="null"> Additional meta data related to transaction (optional) </param>
/// </function>
public static function InvokeCallback($callbackUrl, $transactionId, $orderId, $amount, $currency, $metaData = null)
{
if (is_string($callbackUrl) === false || is_string($transactionId) === false || is_string($orderId) === false || is_int($amount) === false || is_string($currency) === false || ($metaData !== null && ($metaData instanceof PSPPaymentMetaData) === false))
throw new Exception("Invalid argument(s) passed to InvokeCallback(string, string, string, integer, string[, PSPPaymentMetaData])");
if (is_numeric($currency) === true)
$currency = self::NumericValueToCurrencyCode($currency); // Ensure consistency: Always pass currency name (e.g. USD) rather than numeric value (e.g. 840)
$data = array();
$data["TransactionId"] = $transactionId;
$data["OrderId"] = $orderId;
$data["Amount"] = (string)$amount;
$data["Currency"] = $currency;
//$data["Checksum"] = md5(self::getEncryptionKey() . $transactionId . $orderId . $amount . $currency);
if ($metaData !== null)
{
$data["MetaData_Card_Type"] = $metaData->GetCard()->Type();
$data["MetaData_Card_Identifier"] = $metaData->GetCard()->Identifier();
$data["MetaData_Card_ExpiryMonth"] = (string)$metaData->GetCard()->ExpiryMonth();
$data["MetaData_Card_ExpiryYear"] = (string)$metaData->GetCard()->ExpiryYear();
$data["MetaData_Customer_Country"] = $metaData->GetCustomer()->Country();
$data["MetaData_Customer_IpAddress"] = $metaData->GetCustomer()->IpAddress();
}
$checksumString = self::getEncryptionKey();
foreach (self::getChecksumKeys() as $key)
{
if (array_key_exists($key, $data) === true) // MetaData might not have been provided
{
$checksumString .= $data[$key];
}
}
$data["Checksum"] = md5($checksumString);
return self::Post($callbackUrl, $data);
}
/// <function container="PSP" name="GetCallbackData" access="public" static="true" returns="object[]">
/// <description>
/// Securely obtain data sent to application callback specified in RedirectToPaymentForm(..).
/// This function takes care of ensuring data integrity - an exception is thrown
/// if data has been tampered with.
/// Data is returned in an associative array containing the following keys:
/// - TransactionId (string value): Used to capture or cancel payment - empty string if not supported.
/// - OrderId (string value).
/// - Amount (integer value).
/// - Currency (string value): ISO 4217 (e.g. USD, GBP, or USD).
/// - MetaData (instance of PSPPaymentMetaData if provided by Payment Service Provider Module, otherwise null)
/// </description>
/// </function>
public static function GetCallbackData()
{
$transactionId = (isset($_POST["TransactionId"]) ? $_POST["TransactionId"] : null);
$orderId = (isset($_POST["OrderId"]) ? $_POST["OrderId"] : null);
$amount = (isset($_POST["Amount"]) ? (int)$_POST["Amount"] : -1);
$currency = (isset($_POST["Currency"]) ? $_POST["Currency"] : null);
$checksum = (isset($_POST["Checksum"]) ? $_POST["Checksum"] : null);
//$newChecksum = md5(self::getEncryptionKey() . $transactionId . $orderId . $amount . $currency);
$newChecksum = self::getEncryptionKey();
foreach (self::getChecksumKeys() as $key)
{
if (array_key_exists($key, $_POST) === true) // MetaData might not have been provided
{
$newChecksum .= $_POST[$key];
}
}
$newChecksum = md5($newChecksum);
if ($newChecksum !== $checksum)
throw new Exception("SecurityException: Integrity check failed - mismatching checksums");
$metaData = null;
if (isset($_POST["MetaData_Card_Type"]) === true)
{
$metaData = new PSPPaymentMetaData();
$metaData->GetCard()->Type($_POST["MetaData_Card_Type"]);
$metaData->GetCard()->Identifier($_POST["MetaData_Card_Identifier"]);
$metaData->GetCard()->ExpiryMonth((int)$_POST["MetaData_Card_ExpiryMonth"]);
$metaData->GetCard()->ExpiryYear((int)$_POST["MetaData_Card_ExpiryYear"]);
$metaData->GetCustomer()->Country($_POST["MetaData_Customer_Country"]);
$metaData->GetCustomer()->IpAddress($_POST["MetaData_Customer_IpAddress"]);
}
return array("TransactionId" => $transactionId, "OrderId" => $orderId, "Amount" => (int)$amount, "Currency" => $currency, "MetaData" => $metaData);
}
// Configuration
/// <function container="PSP" name="GetConfig" access="public" static="true" returns="string[]">
/// <description>
/// Used by PSPM to obtain associative configuration array
/// defined in Config.php with key/value pairs </description>
/// <param name="provider" type="string"> Name of PSPM </param>
/// </function>
public static function GetConfig($provider)
{
if (is_string($provider) === false)
throw new Exception("Invalid argument passed to GetConfig(string)");
self::ensureProviderConfig($provider);
return self::$configurations[$provider];
}
/// <function container="PSP" name="GetProviderUrl" access="public" static="true" returns="string">
/// <description> Returns external URL to folder containing PSPM </description>
/// <param name="provider" type="string"> Name of PSPM </param>
/// </function>
public static function GetProviderUrl($provider)
{
if (is_string($provider) === false)
throw new Exception("Invalid argument passed to GetProviderUrl(string)");
self::ensureBaseConfig();
return self::$baseConfig["BaseUrl"] . "/" . $provider;
}
// Conversion
/// <function container="PSP" name="CurrencyCodeToNumericValue" access="public" static="true" returns="string">
/// <description>
/// Converts a currency code (e.g. USD) to its numeric equivalent (e.g. 840).
/// Value is returned as string to preserve any leading zeros.
/// </description>
/// <param name="currencyCode" type="string"> Alphabetical currency code as defined by ISO 4217 </param>
/// </function>
public static function CurrencyCodeToNumericValue($currencyCode)
{
if (is_string($currencyCode) === false)
throw new Exception("Invalid argument passed to CurrencyCodeToNumericValue(string)");
self::ensureCurrencies();
if (isset(self::$currencies[$currencyCode]) === false)
throw new Exception("No numeric equivalent to '" . $currencyCode . "' found - pass a valid value such as USD, EUR, GBP, etc.");
return self::$currencies[$currencyCode]; // Numeric values are stored as strings to preserve any leading zeros (e.g. ALL = 008)
}
/// <function container="PSP" name="NumericValueToCurrencyCode" access="public" static="true" returns="string">
/// <description>
/// Converts a numeric concurrency representation (e.g. 840) to its alphabetical equivalent (e.g. USD)
/// </description>
/// <param name="numericCurrencyValue" type="string"> Numeric currency representation as defined by ISO 4217 </param>
/// </function>
public static function NumericValueToCurrencyCode($numericCurrencyValue)
{
if (is_string($numericCurrencyValue) === false)
throw new Exception("Invalid argument passed to NumericValueToCurrencyCode(string)");
self::ensureCurrencies();
if (isset(self::$numCurrencies[$numericCurrencyValue]) === false)
throw new Exception("No currency name equivalent to '" . $numericCurrencyValue . "' found - pass a valid numeric currency value such as 840 for USD, 978 for EUR, 826 for GBP, etc.");
return self::$numCurrencies[$numericCurrencyValue]; // Numeric values are stored as strings to preserve any leading zeros (e.g. ALL = 008)
}
// Logging
/// <function container="PSP" name="IsLoggingEnabled" access="public" static="true" returns="boolean">
/// <description> Returns a value indicating whether logging is enabled or not </description>
/// </function>
public static function IsLoggingEnabled()
{
self::ensureBaseConfig();
return (self::$baseConfig["LogFile"] !== "" && self::$baseConfig["LogMode"] !== "Disabled");
}
/// <function container="PSP" name="GetLogMode" access="public" static="true" returns="string">
/// <description> Returns a value indicating the current logging mode (Disabled, Simple, or Full) </description>
/// </function>
public static function GetLogMode()
{
self::ensureBaseConfig();
return self::$baseConfig["LogMode"];
}
/// <function container="PSP" name="Log" access="public" static="true">
/// <description> Log message to log file - nothing will be logged if logging has been disabled </description>
/// <param name="msg" type="string"> Message to log </param>
/// </function>
public static function Log($msg)
{
self::ensureBaseConfig();
if (self::IsLoggingEnabled() === true)
{
$path = self::$baseConfig["LogFile"];
// Make sure log file can be written
$match = array(); // 0 = full match, 1 = first capture group (folder path), 2 = second capture group (filename)
preg_match("/(.*)\\/(.*)/", $path, $match);
$folderPath = "";
$filename = "";
if (count($match) === 0) // E.g. $path = PSPI_Log.txt
{
$folderPath = dirname(__FILE__);
$filename = $path;
}
else // E.g. $path = path/to/logs/PSPI_Log.txt or $path = path/to/logs/
{
$folderPath = $match[1];
$filename = ($match[2] !== "" ? $match[2] : "PSPI.log");
}
if ($folderPath[0] !== "/") // Path relative to PSPI package (considered absolute if starting with a slash)
$folderPath = dirname(__FILE__) . "/" . $folderPath;
$path = $folderPath . "/" . $filename;
if (file_exists($path) === true && is_writable($path) === false)
throw new Exception("Log file '" . $path . "' is not writable");
else if (is_writable($folderPath) === false)
throw new Exception("Log file cannot be created - folder '" . $folderPath . "' is not writable");
// Create log entry
// Prevent annoying warning:
// Strict Standards: date() [function.date]: It is not safe to rely on the system's timezone settings
date_default_timezone_set("UTC");
$log = "";
$log .= "\n====================================";
$log .= "\nTime: " . date("Y-m-d H:i:s");
$log .= "\n====================================";
$log .= "\n" . $msg;
if (self::$baseConfig["LogMode"] === "Full")
{
$jsonData = file_get_contents("php://input"); // Empty string if no input was provided
$jsonArray = json_decode($jsonData, true); // Return null if no data, null, or invalid JSON was provided
$log .= "\n";
$log .= "JSON:" . print_r($jsonArray, true);
$log .= "\$_GET:" . print_r($_GET, true);
$log .= "\$_POST:" . print_r($_POST, true);
//$log .= "\$_SERVER:" . print_r($_SERVER, true);
}
else
{
$log .= "\n";
}
// Save log entry
@file_put_contents($path, $log, FILE_APPEND);
}
}
/// <function container="PSP" name="GetTestMode" access="public" static="true" returns="boolean">
/// <description>
/// Returns a value indicating whether transactions should be carried
/// out in test mode, meaning no money should be charged when testing.
/// </description>
/// </function>
public static function GetTestMode()
{
self::ensureBaseConfig();
return self::$baseConfig["TestMode"];
}
// Private
private static function ensureBaseConfig()
{
if (self::$baseConfig === null)
{
require_once(dirname(__FILE__) . "/Config.php");
if (isset($config["ConfigPath"]) && $config["ConfigPath"] !== "") // Handle alternative configuration folder
{
$configPath = $config["ConfigPath"];
$configPath = (($configPath[0] !== "/") ? dirname(__FILE__) . "/" : "") . $configPath; // Turn into absolute path if relative path was specified
$configPath = (($configPath[strlen($configPath) - 1] === "/") ? substr($configPath, 0, -1) : $configPath); // Remove trailing slash if defined
$configFile = $configPath . "/Config.php";
if (file_exists($configFile) === false)
throw new Exception("PSPI configuration file '" . $configFile . "' not found");
require_once($configFile);
$config["ConfigPath"] = $configPath;
}
self::$baseConfig = $config;
}
}
private static function ensureProviderConfig($provider)
{
if (is_string($provider) === false)
throw new Exception("Invalid argument passed to ensureProviderConfig(string)");
if (isset(self::$configurations[$provider]) === false)
{
self::ensureBaseConfig();
if (isset(self::$baseConfig["ConfigPath"]) && self::$baseConfig["ConfigPath"] !== "")
require_once(self::$baseConfig["ConfigPath"] . "/" . $provider . "/Config.php");
else
require_once(dirname(__FILE__) . "/" . $provider . "/Config.php");
self::$configurations[$provider] = $config;
}
}
private static function ensureCurrencies()
{
if (self::$currencies === null)
{
require_once(dirname(__FILE__) . "/Currencies.php");
self::$currencies = $currencies;
self::$numCurrencies = array();
foreach ($currencies as $key => $value)
self::$numCurrencies[$value] = $key;
}
}
private static function getEncryptionKey()
{
self::ensureBaseConfig();
return self::$baseConfig["EncryptionKey"];
}
private static function getChecksumKeys()
{
return array(
"TransactionId",
"OrderId",
"Amount",
"Currency",
"MetaData_Card_Type",
"MetaData_Card_Identifier",
"MetaData_Card_ExpiryMonth",
"MetaData_Card_ExpiryYear",
"MetaData_Customer_Country",
"MetaData_Customer_IpAddress"
);
}
}
/// <container name="PSPPaymentMetaData">
/// Class representing payment metadata
/// </container>
class PSPPaymentMetaData
{
private $card = null;
private $customer = null;
/// <function container="PSPPaymentMetaData" name="PSPPaymentMetaData" access="public">
/// <description> Create instance of PSPPaymentMetaData </description>
/// </function>
public function __construct()
{
$this->card = new PSPCardDetails();
$this->customer = new PSPCustomerDetails();
}
/// <function container="PSPPaymentMetaData" name="GetCard" access="public" returns="PSPCardDetails">
/// <description> Get credit card information </description>
/// </function>
public function GetCard()
{
return $this->card;
}
/// <function container="PSPPaymentMetaData" name="GetCustomer" access="public" returns="PSPCustomerDetails">
/// <description> Get customer information </description>
/// </function>
public function GetCustomer()
{
return $this->customer;
}
}
/// <container name="PSPCardDetails">
/// Class representing credit card details
/// </container>
class PSPCardDetails
{
private $type = ""; // E.g. Visa or MasterCard
private $identifier = ""; // Last 4 digits, e.g. 0182 - string to preserve leading zeros
private $expiresMonth = -1; // Expiry month with 1 being January and 12 being December
private $expiresYear = -1; // Expiry year, e.g. 2020
/// <function container="PSPCardDetails" name="Type" access="public" returns="string">
/// <description> Get/set credit card type (e.g. VISA, Mastercard, etc.) </description>
/// <param name="newValue" type="string" default="null"> Updates credit card type if provided </param>
/// </function>
public function Type($newValue = null)
{
if ($newValue !== null && is_string($newValue) === false)
throw new Exception("Invalid argument passed to Type([string])");
if ($newValue !== null)
$this->type = $newValue;
return $this->type;
}
/// <function container="PSPCardDetails" name="Identifier" access="public" returns="string">
/// <description> Get/set credit card identifier (last 4 digits) </description>
/// <param name="newValue" type="string" default="null"> Updates credit card identifier if provided </param>
/// </function>
public function Identifier($newValue = null)
{
if ($newValue !== null && is_string($newValue) === false)
throw new Exception("Invalid argument passed to Identifier([string])");
if ($newValue !== null)
$this->identifier = $newValue;
return $this->identifier;
}
/// <function container="PSPCardDetails" name="ExpiryMonth" access="public" returns="integer">
/// <description> Get/set month credit card expires (1 = January, 12 = December) </description>
/// <param name="newValue" type="integer" default="-1"> Updates expiry month for credit card if provided </param>
/// </function>
public function ExpiryMonth($newValue = -1)
{
if ($newValue !== -1 && is_integer($newValue) === false)
throw new Exception("Invalid argument passed to ExpiryMonth([integer])");
if ($newValue !== -1)
$this->expiresMonth = $newValue;
return $this->expiresMonth;
}
/// <function container="PSPCardDetails" name="ExpiryYear" access="public" returns="integer">
/// <description> Get/set year credit card expires (e.g. 2020) </description>
/// <param name="newValue" type="integer" default="-1"> Updates expiry year for credit card if provided </param>
/// </function>
public function ExpiryYear($newValue = -1)
{
if ($newValue !== -1 && is_integer($newValue) === false)
throw new Exception("Invalid argument passed to ExpiryYear([integer])");
if ($newValue !== -1)
$this->expiresYear = $newValue;
return $this->expiresYear;
}
}
/// <container name="PSPCustomerDetails">
/// Class representing customer details
/// </container>
class PSPCustomerDetails
{
private $country = "";
private $ip = "";
/// <function container="PSPCustomerDetails" name="Country" access="public" returns="string">
/// <description> Get/set customer's country </description>
/// <param name="newValue" type="string" default="null"> Updates country if provided </param>
/// </function>
public function Country($newValue = null)
{
if ($newValue !== null && is_string($newValue) === false)
throw new Exception("Invalid argument passed to Country([string])");
if ($newValue !== null)
$this->country = $newValue;
return $this->country;
}
/// <function container="PSPCustomerDetails" name="IpAddress" access="public" returns="string">
/// <description> Get/set customer's IP address </description>
/// <param name="newValue" type="string" default="null"> Updates IP address if provided </param>
/// </function>
public function IpAddress($newValue = null)
{
if ($newValue !== null && is_string($newValue) === false)
throw new Exception("Invalid argument passed to IpAddress([string])");
if ($newValue !== null)
$this->ip = $newValue;
return $this->ip;
}
}
// ======================================================================================
// Error handling - only in effect if logging has been configured
// ======================================================================================
function PSPErrorHandler($errNo, $errMsg, $errFile, $errLine)
{
PSP::Log("PSP - unhandled error occurred:\nError ID: " . $errNo . "\nError message: " . $errMsg . "\nFile: " . $errFile . "\nLine: " . $errLine);
return false; // Return control to PHP's error handler
}
function PSPExceptionHandler($ex) // The $ex argument may be of type Exception or Error on PHP 7 (both implements Throwable) while only of type Exception prior to PHP 7 (http://php.net/manual/en/function.set-exception-handler.php)
{
$errNo = $ex->getCode();
$errMsg = $ex->getMessage();
$errFile = $ex->getFile();
$errLine = $ex->getLine();
try
{
PSP::Log("PSP - unhandled exception occurred:\nError ID: " . $errNo . "\nError message: " . $errMsg . "\nFile: " . $errFile . "\nLine: " . $errLine . (PSP::GetLogMode() === "Full" ? "\nStackTrace: " . $ex->getTraceAsString() : ""));
}
catch (Exception $excp)
{
}
header("HTTP/1.1 500 Internal Server Error");
//header("Content-Type: text/html; charset=ISO-8859-1");
echo "<b>An unhandled exception occurred</b><br><br>";
echo $ex->getMessage();
echo "<br><br><b>Stack trace</b><br><pre>";
echo $ex->getTraceAsString();
echo "</pre>";
}
if (PSP::IsLoggingEnabled() === true)
{
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
set_error_handler("PSPErrorHandler");
set_exception_handler("PSPExceptionHandler");
}
?>