-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfac-api.php
More file actions
1507 lines (1324 loc) · 58.2 KB
/
fac-api.php
File metadata and controls
1507 lines (1324 loc) · 58.2 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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: First Atlantic Commerce Integration
* Plugin URI: https://www.linkedin.com/in/odain-chevannes
* Description: Quick and Dirty integration to handle payment requests through the FAC gateway
* Version: 1.0
* Author: Odain Chevannes
* Author URI: https://www.linkedin.com/in/odain-chevannes
*/
if (!defined('ABSPATH')) {
die('You are not allowed to call this page directly.');
}
require_once(__DIR__ . '/XML/Serializer.php');
require_once(__DIR__ . '/XML/Unserializer.php');
// Modification Types. psuedo enum
/**
* Class ModificationTypes
*/
final class ModificationTypes
{
const Capture = 1;
const Refund = 2;
const Reversal = 3;
const Cancel = 4;
}
// exceptions
class FacAuthorizationException extends Exception
{
}
add_action('rest_api_init', 'FacApi::register_endpoints');
add_action('admin_menu', 'FacApi::fac_admin_menu');
add_action('admin_init', 'FacApi::fac_settings_init');
add_action('fac_recurring_daily_txn', 'FacApi::schedule_recurring_txns');
register_activation_hook(__FILE__, "FacApi::init");
register_deactivation_hook(__FILE__, 'FacApi::fac_deactivation');
register_uninstall_hook(__FILE__, "FacApi::fac_uninstall");
add_filter("plugin_action_links_" . plugin_basename(__FILE__), 'FacApi::fac_plugin_settings_link');
class FacApi
{
// we call the soap action to get the token we need to bring up the remote page
// so that we don't have to handle the card number
/**
* @param WP_REST_Request $request
* @return string[]
* @throws SoapFault
*/
public static function get_hosted_page(WP_REST_Request $request)
{
$opts = $options = get_option('fac_api_options');
// echo $opts['test_mode'];
// FAC Integration Domain
$domain = $opts['fac_api_field_test_mode'] == true ? $opts['fac_api_field_test_domain'] : $opts['fac_api_field_live_domain'];
// Ensure you append the ?wsdl query string to the URL
$wsdlurl = 'https://' . $domain . '/PGService/HostedPage.svc?wsdl';
$soapUrl = 'https://' . $domain . '/PGService/HostedPage.svc';
// Set up client to use SOAP 1.1 and NO CACHE for WSDL. You can choose between
// exceptions or status checking. Here we use status checking. Trace is for Debug only
// Works better with MS Web Services where
// WSDL is split into several files. Will fetch all the WSDL up front.
$options = array(
'location' => $soapUrl,
'soap_version' => SOAP_1_1,
'exceptions' => 0,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
);
// WSDL Based calls use a proxy, so this is the best way
// to call FAC PG Operations.
$client = new SoapClient($wsdlurl, $options);
// This should not be in your code in plain text!
$password = $opts['fac_api_field_transaction_pwd'];
// Use your own FAC ID
$facId = $opts['fac_api_field_merchant_id'];
// Acquirer is always this
$acquirerId = $opts['fac_api_field_acquirer_id'];
// THESE next variables COME FROM THE PREVIOUS PAGE (hence $_POST) but you could drive
// these from any source such as config files, server cache etc.
// Must be Unique per order. Put your own format here. The field allows up to 150
// alphanumeric characters.
$orderNumber = $_POST["OrderId"];
// Passed in as a decimal but 12 chars is required
$amount = $_POST["Amount"];
// Page Set
$pageset = $_POST["PageSet"];
// Page Name
$pagename = $_POST["PageName"];
// TransCode
$transCode = $_POST["TransCode"];
// Where the response will end up. Should be a page your site and will get two parameters
// ID = Single Use Key passed to payment page and RespCode = normal response code for Auth
$CardHolderResponseUrl = $_POST["CardHolderResponseUrl"];
// Formatted Amount. Must be in twelve charecter, no decimal place, zero padded format
$amountFormatted = str_pad('' . ($amount * 100), 12, "0", STR_PAD_LEFT);
// 840 = USD, put your currency code here
$currency = '840';
// Each call must have a signature with the password as the shared secret
$signature = self::Sign($password, $facId, $acquirerId, $orderNumber, $amountFormatted, $currency);
// this is <userid>_<product_code>_<order_id>
$txn_details = explode("_", $orderNumber);
$user_id = $txn_details[0];
// You only need to initialise the message sections you need. So for a basic Auth
// only Credit Cards and Transaction details are required.
// Transaction Details.
$TransactionDetails = array('AcquirerId' => $acquirerId,
'Amount' => $amountFormatted,
'Currency' => $currency,
'CurrencyExponent' => 2,
'IPAddress' => '',
'MerchantId' => $facId,
'OrderNumber' => $orderNumber,
'Signature' => $signature,
'SignatureMethod' => 'SHA1',
'CustomerReference' => $user_id,
'TransactionCode' => 392);
// 128 - return my tokenized PAN dude!
// 256 - 3ds my dude
// 264 - capture auth + 3ds
// 392 - capture auth, 3ds and tokenize
// The request data is named 'Request' for reasons that are not clear!
$HostedPageRequest = array('Request' => array('TransactionDetails' => $TransactionDetails,
'CardHolderResponseURL' => $CardHolderResponseUrl));
// Call the Authorize through the Soap Client
$result = $client->HostedPageAuthorize($HostedPageRequest);
// You should CHECK the results here!!!
// print_r($HostedPageRequest);
// print_r($result);
$returnObj = array(
'status' => '',
'description' => '',
'forwardUrl' => ''
);
if ($result->ResponseCode == 0) {
// Extract Token
$token = $result->HostedPageAuthorizeResult->SingleUseToken;
// Construct the URL. This may be different for Production. Check with FAC
$PaymentPageUrl = 'https://' . $domain . '/MerchantPages/' . $pageset . '/' . $pagename . '/';
// Create the location header to effect a redirect. Add token required by page
$RedirectURL = $PaymentPageUrl . $token;
// Redirect user to the Payment page
$returnObj['status'] = "success";
$returnObj['forwardUrl'] = $RedirectURL;
$returnObj['request'] = $HostedPageRequest;
} else {
$returnObj['status'] = "failure";
$returnObj['description'] = "Error " . $result->ResponseCode . ": " . $result . ResponseCodeDescription;
}
return $returnObj;
}
// This is essentially a web hook
// once the user submits the form to FAC, we need to send another request
// to get the result of that authorization request
public static function get_hosted_page_result(WP_REST_Request $request)
{
$opts = $options = get_option('fac_api_options');
// echo $opts['test_mode'];
// FAC Integration Domain
$domain = $opts['fac_api_field_test_mode'] == true ? $opts['fac_api_field_test_domain'] : $opts['fac_api_field_live_domain'];
// IMPORTANT: Convert URL Parameters to variables
$ID = $_GET['ID'];
$host = 'ecm.firstatlanticcommerce.com';
// Ensure you append the ?wsdl query string to the URL for WSDL URL
$wsdlurl = 'https://' . $domain . '/PGService/HostedPage.svc?wsdl';
// No WSDL parameter for location URL
$loclurl = 'https://' . $domain . '/PGService/HostedPage.svc';
// Set up client to use SOAP 1.1 and NO CACHE for WSDL. You can choose between
// exceptions or status checking. Here we use status checking. Trace is for Debug only
// Works better with MS Web Services where
// WSDL is split into several files. Will fetch all the WSDL up front.
$options = array(
'location' => $loclurl,
'soap_version' => SOAP_1_1,
'exceptions' => 0,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
);
// WSDL Based calls use a proxy, so this is the best way
// to call FAC PG Operations as it creates the methods for you
$client = new SoapClient($wsdlurl, $options);
// Call the HostedPageResults through the Client. Note the param
// name is case sensitive, so 'Key' does not work.
$result = $client->HostedPageResults(array('key' => $ID));
// NOW: You have access to all the response fields and can evaluate as you want to
// and use them to display something to the user in an HTML page like the HTML snippet
// below. It is very simple and you have not had any exposure to the card number at all.
// While it is not necessary to make this soap call, it is advisable that you implement this
// and get the full response details to ensure the correct amount has been charged etc.
// You should also store the results in case of any chargeback issues and to check the response
// code has not been tampered with.
if ($result->HostedPageResultsResult->AuthResponse->CreditCardTransactionResults->ReasonCode != 1) {
// echo "<h1>";
// echo FacApi::mepr_remove_current_member();
// echo "</h1>";
FacApi::mepr_fail_page($result->HostedPageResultsResult->AuthResponse->CreditCardTransactionResults->ReasonCodeDescription);
} else {
//$tokenized_pan = $result->HostedPageResultsResult->AuthResponse->CreditCardTransactionResults->TokenizedPAN;
self::write_log($result);
$txn_amount = ltrim($result->HostedPageResultsResult->PurchaseAmount, "0");
$txn_amount = substr_replace($txn_amount, ".", -2, 0);
$orderId = $result->HostedPageResultsResult->AuthResponse->OrderNumber;
$token_pan = $result->HostedPageResultsResult->AuthResponse->CreditCardTransactionResults->TokenizedPAN;
try {
// create the recurring txn in memberpress plugin
$create_sub_request = FacApi::mepr_create_sub($orderId, $txn_amount, implode("|", $result), $token_pan);
if (wp_remote_retrieve_response_code($create_sub_request) == 200) {
// we outta here!
FacApi::mepr_success_page();
} else {
// could not create sub we should reverse transaction
FacApi::modify_trxn($orderId, $txn_amount);
$responseData1 = json_decode(wp_remote_retrieve_body($create_sub_request));
FacApi::mepr_fail_page("Could not create subscription. Payment has been reversed. Details: "
. substr($responseData1->message, 0, 100));
}
} catch (Exception $ex) {
FacApi::mepr_fail_page("Could not create subscription. Payment could not be reversed at this time. " . $ex->getMessage());
}
}
}
/**
* @param string $orderId the order number
* @param string $order_total the transaction amount
* @param string $token_pan the tokenized card number/ card number
* @param string $customer_ref the customer reference number for the tokenized PAN
* @param DateTime $card_exp this is not important when using the tokenize pan
* @param string $cvv the card verification value, this is not needed for tokenized transactions
* @throws FacAuthorizationException
*/
static function authorize_trxn($orderId, $order_total, $token_pan, $customer_ref,
$card_exp = null, $cvv = "123")
{
$opts = $options = get_option('fac_api_options');
// XML Urls are named after the Operation in a Rest-ful manner
$url = $opts['fac_api_field_test_mode'] == true ?
$opts['fac_api_field_test_url'] : $opts['fac_api_field_live_url'];
// This should not be in your code in plain text!
$password = $opts['fac_api_field_transaction_pwd'];
// Use your own FAC ID
$facId = $opts['fac_api_field_merchant_id'];
// Acquirer is always this
$acquirerId = $opts['fac_api_field_acquirer_id'];
// This is set in the merchant portal. transactions can fail if time is behind keep this updated
$timeZone = $opts['fac_api_field_time_zone_gmt'];
// Must be Unique per order. Put your own format here
$orderNumber = $orderId;
// 12 chars, always, no decimal place
$amount = FacApi::format_float($order_total);
// Formatted Amount. Must be in twelve charecter, no decimal place, zero padded format
$amountFormatted = str_pad('' . ($amount * 100), 12, "0", STR_PAD_LEFT);
// 840 = USD, put your currency code here
$currency = '840';
$signature = FacApi::Sign($password, $facId, $acquirerId, $orderNumber, $amountFormatted,
$currency);
// You only need to initialise the message sections you need. So for a basic
//Auth
// only Credit Cards and Transaction details are required.
// Card Details. Arrays serialise to elements in XML/SOAP
$CardDetails = array('CardCVV2' => $cvv,
'CardExpiryDate' => date("my", $card_exp),
'CardNumber' => $token_pan,
'IssueNumber' => '',
'StartDate' => '');
// Transaction Details.
$TransactionDetails = array('Amount' => $amountFormatted,
'Currency' => $currency,
'CurrencyExponent' => 2,
'IPAddress' => '',
'MerchantId' => $facId,
'OrderNumber' => $orderNumber,
'Signature' => $signature,
'AcquirerId' => $acquirerId,
'SignatureMethod' => 'SHA1',
'TransactionCode' => '0',
'CustomerReference' => $customer_ref);
// The request data is named 'Request' for reasons that are not clear!
$AuthorizeRequest = array(
'TransactionDetails' => $TransactionDetails,
'CardDetails' => $CardDetails
);
$options = array(
"indent" => " ",
"linebreak" => "\n",
"typeHints" => false,
"addDecl" => true,
"encoding" => "UTF-8",
"rootName" => "AuthorizeRequest",
"defaultTagName" => "item",
"rootAttributes" => array("xmlns" =>
"http://schemas.firstatlanticcommerce.com/gateway/data")
);
$serializer = new XML_Serializer($options);
if ($serializer->serialize($AuthorizeRequest)) {
$xmlRequest = $serializer->getSerializedData();
//debug
//echo '<pre>';
// htmlspecialchars($xmlRequest);
//echo '</pre>';
$ch = curl_init($url);
//curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// Let's convert to an Object graph, easier to process
$options = array('complexType' => 'object');
$deserializer = new XML_Unserializer($options);
// Pass in the response XML as a string
$result = $deserializer->unserialize($response, false);
// As with Serializing, we must call getUnserialzedData afterwards
$AuthorizeResponse = $deserializer->getUnserializedData();
// Display the result objects
//echo '<h2>Result</h2><pre>';
//print_r($AuthorizeResponse);
if ($AuthorizeResponse->CreditCardTransactionResults->ReasonCode == 1) {
return $AuthorizeResponse;
} else {
$msg = $AuthorizeResponse->CreditCardTransactionResults->ReasonCode . ' - ' . $AuthorizeResponse->CreditCardTransactionResults->ReasonCodeDescription;
throw new FacAuthorizationException($msg);
}
//echo '</pre>';
} else {
throw new FacAuthorizationException(__('Can\'t read response from First Atlantic Commerce SOAP Endpoint', 'memberpress'));
}
return false;
}
/**
* Initialize this plugin
*/
static function init()
{
// this file is basically an addon for memberpress
// so we will copy our custom files to the memberpress directories
copy(__DIR__ . "/MeprFirstAtlanticCommerceGateway.php", ABSPATH . "wp-content/plugins/memberpress/app/gateways/MeprFirstAtlanticCommerceGateway.php");
copy(__DIR__ . "/MeprBaseGateway.php", ABSPATH . "wp-content/plugins/memberpress/app/lib/MeprBaseGateway.php");
// create the database for keeping track of recurring transactions
Self::create_plugin_database_table();
// daily sweep for all subs
Self::schedule_recurring_txns();
}
static function fac_deactivation()
{
wp_clear_scheduled_hook('fac_recurring_daily_txn');
}
static function fac_uninstall()
{
FacApi::remove_plugin_database_table();
unlink(ABSPATH . "wp-content/plugins/memberpress/app/gateways/MeprFirstAtlanticCommerceGateway.php");
}
/**
* show settings link on plugin page
*/
static function fac_plugin_settings_link($links)
{
$settings_link = '<a href="https://' . $_SERVER['SERVER_NAME'] . '/wp-admin/admin.php?page=fac-api">Settings</a>';
array_unshift($links, $settings_link);
return $links;
}
/**
* Register API endpoints
*/
static function register_endpoints()
{
// POST /fac/v1/authorize3ds/check
register_rest_route('fac/v1', 'authorize3ds/check', [
'methods' => 'GET',
'callback' => 'FacApi::get_hosted_page_result',
'args' => array(
'ID' => array(
'required' => false,
),
'RespCode' => array(
'required' => false,
),
'ReasonCode' => array(
'required' => false,
)
)
]);
// POST /fac/v1/authorize3ds
register_rest_route('fac/v1', 'authorize3d', [
'methods' => 'POST',
'callback' => 'FacApi::get_hosted_page'
]);
}
/**
* we update the cardholder's token here.
*
* We get the token from the initial 3ds transaction and stored it (if the txn was a recurring txn)
* The token is used to create a secure representation of the card details
* so that we don't have to store the card data on the merchant's end.
*
*/
static function update_tokenized_card($customer_ref, $expiry_date, $pan_token)
{
$opts = $options = get_option('fac_api_options');
// echo $opts['test_mode'];
// FAC Integration Domain
$domain = $opts['fac_api_field_test_mode'] == true ? $opts['fac_api_field_test_domain'] : $opts['fac_api_field_live_domain'];
// Ensure you append the ?wsdl query string to the URL for WSDL URL
$wsdlurl = 'https://' . $domain . '/PGService/Tokenization.svc?wsdl';
// No WSDL parameter for location URL
$loclurl = 'https://' . $domain . '/PGService/Tokenization.svc';
// Set up client to use SOAP 1.1 and NO CACHE for WSDL. You can choose between
// exceptions or status checking. Here we use status checking. Trace is for Debug only
// Works better with MS Web Services where
// WSDL is split into several files. Will fetch all the WSDL up front.
$options = array(
'location' => $loclurl,
'soap_version' => SOAP_1_1,
'exceptions' => 0,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
);
// WSDL Based calls use a proxy, so this is the best way
// to call FAC PG Operations as it creates the methods for you
$client = new SoapClient($wsdlurl, $options);
// This should not be in your code in plain text!
$password = $opts['fac_api_field_transaction_pwd'];
// Use your own FAC ID
$facId = $opts['fac_api_field_merchant_id'];
// Acquirer is always this
$acquirerId = $opts['fac_api_field_acquirer_id'];
// Each call must have a signature with the password as the shared secret
$signature = self::Sign($password, $facId, $acquirerId);
$Request = array('CustomerReference' => $customer_ref,
'ExpiryDate' => $expiry_date,
'MerchantNumber' => $facId,
'TokenPAN' => $pan_token,
'Signature' => $signature
);
// The request data is named 'Request' for reasons that are not clear!
$UpdateTokenRequest = array('Request' => array('CustomerReference' => $customer_ref,
'ExpiryDate' => $expiry_date,
'MerchantNumber' => $facId,
'TokenPAN' => $pan_token,
'Signature' => $signature
));
// Call the Authorize through the Soap Client
$result = $client->UpdateToken($UpdateTokenRequest);
return $result->UpdateTokenResponse->Success;
}
/**
* Gets a secure representation of the customers card detail for future use with the gateway, without storing the
* card details on the merchant's system
* @param string $customer_ref customer reference
* @param string $expiry_date the expiry date of the card
* @param string $pan the card number
* @return mixed
* @throws SoapFault
*/
static function get_tokenized_card($customer_ref, $expiry_date, $pan)
{
$opts = $options = get_option('fac_api_options');
// echo $opts['test_mode'];
// FAC Integration Domain
$domain = $opts['fac_api_field_test_mode'] == true ? $opts['fac_api_field_test_domain'] : $opts['fac_api_field_live_domain'];
// Ensure you append the ?wsdl query string to the URL for WSDL URL
$wsdlurl = 'https://' . $domain . '/PGService/Tokenization.svc?wsdl';
// No WSDL parameter for location URL
$loclurl = 'https://' . $domain . '/PGService/Tokenization.svc';
// Set up client to use SOAP 1.1 and NO CACHE for WSDL. You can choose between
// exceptions or status checking. Here we use status checking. Trace is for Debug only
// Works better with MS Web Services where
// WSDL is split into several files. Will fetch all the WSDL up front.
$options = array(
'location' => $loclurl,
'soap_version' => SOAP_1_1,
'exceptions' => 0,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE
);
// WSDL Based calls use a proxy, so this is the best way
// to call FAC PG Operations as it creates the methods for you
$client = new SoapClient($wsdlurl, $options);
// This should not be in your code in plain text!
$password = $opts['fac_api_field_transaction_pwd'];
// Use your own FAC ID
$facId = $opts['fac_api_field_merchant_id'];
// Acquirer is always this
$acquirerId = $opts['fac_api_field_acquirer_id'];
// Each call must have a signature with the password as the shared secret
$signature = self::Sign($password, $facId, $acquirerId);
$Request =
// The request data is named 'Request' for reasons that are not clear!
$UpdateTokenRequest = array('Request' => array('CustomerReference' => $customer_ref,
'ExpiryDate' => $expiry_date,
'MerchantNumber' => $facId,
'CardNumber' => $pan,
'Signature' => $signature,
'CustomerReference' => $customer_ref
));
// Call the Authorize through the Soap Client
return $client->Tokenize($UpdateTokenRequest);
}
/**
* Table set up to track recurring transaction on the merchant end
*/
static function create_plugin_database_table()
{
global $table_prefix, $wpdb;
$tblname = 'fac_recurring_transaction';
$wp_track_table = $table_prefix . "$tblname";
#Check to see if the table exists already, if not, then create it
if ($wpdb->get_var("show tables like '$wp_track_table'") != $wp_track_table) {
$sql = "CREATE TABLE `" . $wp_track_table . "` ( ";
$sql .= " `id` int(11) NOT NULL auto_increment, ";
$sql .= " `tokenized_pan` varchar(30) NOT NULL, ";
$sql .= " `membership_id` int NOT NULL, ";
$sql .= " `customer_ref` varchar(30) NOT NULL, ";
$sql .= " `txn_amount` varchar(20) NOT NULL, ";
$sql .= " `txn_cycles` varchar(6) NOT NULL, ";
$sql .= " `txn_cycles_num` int NOT NULL, ";
$sql .= " `txn_count` int(11) NOT NULL, ";
$sql .= " `txn_complete` boolean NOT NULL, ";
$sql .= " `interval_type` varchar(20) NOT NULL, ";
$sql .= " `next_execution` datetime NOT NULL, ";
$sql .= " PRIMARY KEY `order_id` (`id`) ";
$sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";
require_once(ABSPATH . '/wp-admin/includes/upgrade.php');
dbDelta($sql);
// self::write_log("==================================");
// self::write_log("EXECUTING SQL");
// self::write_log("==================================");
// self::write_log($sql);
//
// self::write_log("verifying table created");
// self::write_log("show tables like '$wp_track_table'");
// self::write_log($wpdb->get_var("show tables like '$wp_track_table'"));
}
}
static function remove_plugin_database_table()
{
// drop tables
global $table_prefix, $wpdb;
$tblname = 'fac_recurring_transaction';
$wp_track_table = $table_prefix . "$tblname";
$wpdb->query("DROP TABLE IF EXISTS $wp_track_table");
}
/**
* @param string $subId id for the subscription
* @param string $membership_id id for the membership/product being subscribed to
* @param string $customer_reference the unique customer number
* @param string $amount the transaction amount
* @param string $pan the tokenized card number
* @param string $cycles the time interval
* @param int $cycle_num the number of intervals
* @param int $count the number of payments already processed in this subscription
*/
static function db_create_recurring_txn($subId, $membership_id, $customer_reference, $amount, $pan, $cycles, $cycle_num, $count = 1)
{
global $table_prefix, $wpdb;
$tblname = 'fac_recurring_transaction';
$wp_track_table = $table_prefix . "$tblname";
$execution_date = new DateTime();
if ($cycles == 'months')
$execution_date->add(new DateInterval("P1M"));
else if ($cycles == 'years') {
$execution_date->add(new DateInterval("P1Y"));
} else if ($cycles == 'weeks')
$execution_date->add(new DateInterval("P7D"));
$result = $wpdb->insert($wp_track_table, array(
'id' => (int)$subId,
'tokenized_pan' => $pan,
'membership_id' => (int)$membership_id,
'customer_ref' => $customer_reference,
'txn_cycles' => $cycles,
'txn_amount' => $amount,
'txn_cycles_num' => (int)$cycle_num,
'txn_count' => $count,
'interval_type' => $cycles,
'txn_complete' => false,
'next_execution' => $execution_date->format("Y-m-d")
)
);
FacApi::write_log($result);
if ($result == false) {
throw new Exception("could not add txn to database. " . $wpdb->last_error);
}
}
/**
* updates a recurring txn when an authorization is done
* @param string $id the id for the txn in the database
* @param string $next_execution the next execution date for this transaction
* @param string $limit the maximum number of payments to be done
* @param string $count the current transaction number
*/
static function db_record_complete_txn($id, $next_execution=null, $limit = null, $count = null)
{
// we are just going to mak this as complete
if ($limit == null && $count == null && $next_execution=null) {
$limit = 1;
$count = 1;
}
$completed = false;
if ($count >= $limit) {
// if count and limit were specified we want to check if this is the last payment
$completed = true;
}
global $table_prefix, $wpdb;
// get the table name
$tblname = 'fac_recurring_transaction';
$wp_track_table = $table_prefix . "$tblname";
// data to update
$data = array(
'txn_complete' => $completed,
'txn_count' => $count + 1,
'next_execution' => $next_execution);
// clause
$where = array('id' => $id);
// do update in db
$wpdb->update($wp_track_table, $data, $where);
}
/**
* checks the txn table for pending recurring transactions and execute them if they are due today
*/
static function fac_recurring_daily_txn()
{
$today = new DateTime();
$today_str = date("Ymd");
// fetch all the pending transactions
$txns = Self::db_get_recurring_txn();
if ($txns) {
foreach ($txns as $txn) {
$txn_date_str = date("Ymd", strtotime($txn->next_execution));
// should this txn be done today?
if ($txn_date_str == $today_str) {
// create a card expiry date to make this request valid
// any future date is acceptable
$exp = $today->add(new DateInterval("P1Y"));
$execution_date = new DateTime();
if ($txn->interval_type == 'months')
$execution_date->add(new DateInterval("P1M"));
else if ($txn->interval_type == 'years') {
$execution_date->add(new DateInterval("P1Y"));
} else if ($txn->interval_type == 'weeks')
$execution_date->add(new DateInterval("P7D"));
try {
$orderId = "R_" . generateRandomString();
$auth = Self::authorize_trxn(
$orderId,
$txn->txn_amount,
$txn->tokenized_pan,
$txn->customer_ref,
date("Ymd", $exp));
// record the txn in memberpress
self::mepr_create_transaction(
$txn->customer_ref,
$txn->membership_id,
$orderId,
$txn->id,
$txn->txn_amount,
print_r($auth),
false
);
// update this record
Self::db_record_complete_txn($txn->id, date('Y-m-d', $execution_date), $txn->txn_cycles_num, $txn->txn_count + 1);
} catch (Exception $ex) {
Self::write_log($ex);
}
}
}
}
}
/**
* Wordpress logs!
*/
static function write_log($log)
{
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// get sub interval
static function get_subscription_interval($sub)
{
if ($sub->period_type == 'months')
return "M";
else if ($sub->period_type == 'years') {
return "Y";
} else if ($sub->period_type == 'weeks')
return "W";
}
/**
* Find all the pending recurring transactions
*/
static function db_get_recurring_txn()
{
global $wpdb;
global $table_prefix, $wpdb;
$tblname = 'fac_recurring_transaction';
$wp_track_table = $table_prefix . "$tblname";
$execution_date = new DateTime();
return $wpdb->get_results("select * from $wp_track_table " . "txn_complete = false");
}
/**
* create a cron job to check subs and pay the txns that are due
*/
public static function schedule_recurring_txns()
{
if (!wp_next_scheduled('fac_recurring_daily_txn')) {
wp_schedule_event(time(), 'daily', 'fac_recurring_daily_txn');
}
}
/**
* memberpress txn was successful
*/
static function mepr_success_page()
{
$page = "https://" . $_SERVER['SERVER_NAME'] . "/thank-you/";
wp_redirect($page);
exit();
}
/**
* memberpress txn failed
*/
static function mepr_fail_page($err)
{
$paymentFailedPage = "https://" . $_SERVER['SERVER_NAME'] . "/failed-payment?err=" . $err;
wp_redirect($paymentFailedPage);
exit();
}
/**
* @param string $orderId This consist of the user id, product id and order number
* @param string $price The cost of the sub
* @param string $resp the response from the gateway
* @param string $pan the tokenized card number
* @param int $limit maximum number of payment cycles
* @param string $limitType weekly, monthly, yearly etc.
* @param boolean $limit_cycles is this trxn limited
*/
static function mepr_create_sub($orderId, $price, $resp, $pan, $limit = 1, $limitType = "years", $limit_cycles = false)
{
$opts = $options = get_option('fac_api_options');
$meprPassword = $opts["fac_api_field_time_mepr_api_pwd"];
$url = "https://" . $_SERVER['SERVER_NAME'] . "/wp-json/mp/v1/subscriptions";
$headers = array("MEMBERPRESS-API-KEY" => $meprPassword);
$txn_details = explode("_", $orderId);
$user_id = $txn_details[0];
$membership_id = $txn_details[1];
$subId = $txn_details[2];
// get the details for the membership we are adding the user to
$membership = FacApi::mepr_get_membership($membership_id);
// get the user's current subs
$subs = FacApi::mepr_get_subs();
if (isset($membership)) {
$limitType = $membership->period_type;
$limit = $membership->limit_cycles_num;
$limit_cycles = $membership->limit_cycles;
}
// delete existing subs
if (isset($subs)) {
foreach ($subs as $item) {
if ($item->member->id == $user_id) {
FacApi::mepr_delete_sub($item->id);
FacApi::db_record_complete_txn($item->id);
}
}
}
$data = array(
"subscr_id" => $subId,
"member" => $user_id,
"period_type" => $limitType,
"membership" => $membership_id,
"gateway" => "qkh4bw-1x7", // not sure if this will change
"limit_cycles_action" => "expire",
"limit_cycles" => $limit_cycles,
"limit_cycles_num" => $limit,
"status" => "active",
"total" => $price,
"response" => $resp,
"created_at" => date('c')
);
$result = wp_remote_post($url, array(
"body" => $data,
"method" => "POST",
"headers" => $headers
));
FacApi::write_log("=================================");
FacApi::write_log("CREATING SUBSCRIPTION");
FacApi::write_log("=================================");
FacApi::write_log($result);
// sub created
if (wp_remote_retrieve_response_code($result) == 200) {
$sub = json_decode(wp_remote_retrieve_body($result));
// create the txn for the sub
$txn_result = FacApi::mepr_create_transaction(
$user_id,
$membership_id,
date("Ymdgi") . "_" . $orderId,
$sub->id,
$price,
"",
true
);
FacApi::write_log("=================================");
FacApi::write_log("CREATING TRANSACTION");
FacApi::write_log("=================================");
FacApi::write_log($txn_result);
if (wp_remote_retrieve_response_code($txn_result) != 200) {
$responseData = json_decode(wp_remote_retrieve_body($txn_result));
throw new Exception(substr($responseData->message, 0, 100));
}
$limit = $limit_cycles ? $limit : 99999; // no limit
// save this to db for future processing
FacApi::db_create_recurring_txn($sub->id, $user_id, $txn_details, $price, $pan, $limitType, $limit, 1);
return $txn_result;
}
//return $result;
}
static function mepr_delete_sub($id)
{
$opts = $options = get_option('fac_api_options');
$meprPassword = $opts["fac_api_field_time_mepr_api_pwd"];
$url = "https://" . $_SERVER['SERVER_NAME'] . "/wp-json/mp/v1/subscriptions/" . $id;
$basicauth = 'Basic ' . base64_encode($opts['fac_api_field_admin_username'] . ':' . $opts['fac_api_field_admin_password']);
$headers = array(
"MEMBERPRESS-API-KEY" => $meprPassword,
'Authorization' => $basicauth);
$result = wp_remote_post($url, array(
"method" => "DELETE",
"headers" => $headers
));
FacApi::write_log("============================================================");
FacApi::write_log("DELETING SUBSCRIPTION WITH ID " . $id);
FacApi::write_log("============================================================");
FacApi::write_log($result);
return $result;
}
static function mepr_get_membership($id)
{
$opts = $options = get_option('fac_api_options');
$meprPassword = $opts["fac_api_field_time_mepr_api_pwd"];
$url = "https://" . $_SERVER['SERVER_NAME'] . "/wp-json/mp/v1/memberships/" . $id;
$headers = array("MEMBERPRESS-API-KEY" => $meprPassword);
$result = wp_remote_get($url, array(
"headers" => $headers
));
FacApi::write_log($result);
if (wp_remote_retrieve_response_code($result) == 200) {
return json_decode($result["body"]);