-
Notifications
You must be signed in to change notification settings - Fork 38
/
AfricasTalkingGateway.cs
1781 lines (1630 loc) · 66.1 KB
/
AfricasTalkingGateway.cs
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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AfricasTalkingGateway.cs" company="Africa's Talking">
// 2019
// </copyright>
// <summary>
// Defines the AfricasTalkingGateway type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace AfricasTalkingCS
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PhoneNumbers;
/// <summary>
/// The africas talking gateway class. Accepting sandbox as an environment
/// </summary>
public class AfricasTalkingGateway
{
private readonly string _username;
private readonly string _apikey;
private readonly string _environment;
private int _responseCode;
private JsonSerializer _serializer;
private readonly bool _debug = false;
/// <summary>
/// Initializes a new instance of the <see cref="AfricasTalkingGateway"/> class.
/// </summary>
/// <param name="username">
/// The username. Expects "sandbox" or Actual AfricasTalking username
/// </param>
/// <param name="apikey">
/// The apikey.
/// </param>
public AfricasTalkingGateway(string username,string apikey)
{
if (username == "sandbox")
{
_username = "sandbox";
_environment = "sandbox";
_apikey = apikey;
}
else
{
_username = username;
_apikey = apikey;
_environment = "production";
}
_serializer = new JsonSerializer();
}
/// <summary>
/// Initializes a new instance of the <see cref="AfricasTalkingGateway"/> class.
/// </summary>
/// <param name="username">
/// The username.
/// </param>
/// <param name="apikey">
/// The apikey.
/// </param>
/// <param name="environment">
/// The environment.
/// </param>
public AfricasTalkingGateway(string username,string apikey,string environment)
{
_username = username;
_apikey = apikey;
_environment = environment;
_serializer = new JsonSerializer();
}
/// <summary>
/// The send message method.
/// </summary>
/// <param name="to">
/// The Recipient(s).
/// </param>
/// <param name="message">
/// The message content.
/// </param>
/// <param name="from">
/// The Sender.
/// </param>
/// <param name="bulkSmsMode">
/// The bulk SMS mode: set 1 for Bulk SMS
/// </param>
/// <param name="options">
/// The Options for premium SMS.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by the gateway
/// </exception>
public dynamic SendMessage(
string to,
string message,
string from = null,
int bulkSmsMode = -1,
Hashtable options = null)
{
// TODO Convert options to type IDictionary
string[] numbers = to.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
var isValidphoneNumber = IsPhoneNumber(numbers);
if (to.Length == 0 || message.Length == 0 || !isValidphoneNumber)
{
throw new AfricasTalkingGatewayException("The message is either empty or phone number is not valid");
}
else
{
try
{
var data = new Hashtable
{
["username"] = this._username,
["to"] = to,
["message"] = message
};
if (from != null)
{
data["from"] = from;
data["bulkSMSMode"] = Convert.ToString(bulkSmsMode);
if (options != null)
{
if (options.Contains("keyword"))
{
data["keyword"] = options["keyword"];
}
if (options.Contains("linkId"))
{
data["linkId"] = options["linkId"];
}
if (options.Contains("enqueue"))
{
data["enqueue"] = options["enqueue"];
}
if (options.Contains("retryDurationInHours"))
{
data["retryDurationInHours"] = options["retryDurationInHours"];
}
}
}
var response = this.SendPostRequest(data, this.BulkSMSUrl);
dynamic json = JObject.Parse(response);
return json;
}
catch (AfricasTalkingGatewayException e)
{
throw new AfricasTalkingGatewayException(e);
}
}
}
/// <summary>
/// The send premium message method.
/// </summary>
/// <param name="to">
/// The Recipient(s).
/// </param>
/// <param name="message">
/// The message content.
/// </param>
/// <param name="from">
/// The Sender.
/// </param>
/// <param name="bulkSmsMode">
/// The bulk SMS mode: set 1 for Bulk SMS
/// </param>
/// <param name="options">
/// The Options for premium SMS.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by the gateway
/// </exception>
public dynamic SendPremiumMessage(
string to,
string message,
string from ,
int bulkSmsMode = 0,
Hashtable options = null)
{
// TODO Convert options to type IDictionary
string[] numbers = to.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
var isValidphoneNumber = IsPhoneNumber(numbers);
if (to.Length == 0 || message.Length == 0 || !isValidphoneNumber)
{
throw new AfricasTalkingGatewayException("The message is either empty or phone number is not valid");
}
else
{
try
{
var data = new Hashtable
{
["username"] = this._username,
["to"] = to,
["message"] = message
};
if (from != null)
{
data["from"] = from;
data["bulkSMSMode"] = Convert.ToString(bulkSmsMode);
if (options != null)
{
if (options.Contains("keyword"))
{
data["keyword"] = options["keyword"];
}
if (options.Contains("linkId"))
{
data["linkId"] = options["linkId"];
}
if (options.Contains("enqueue"))
{
data["enqueue"] = options["enqueue"];
}
if (options.Contains("retryDurationInHours"))
{
data["retryDurationInHours"] = options["retryDurationInHours"];
}
}
}
var response = this.SendPostRequest(data, this.PremiumSMSURL);
dynamic json = JObject.Parse(response);
return json;
}
catch (AfricasTalkingGatewayException e)
{
throw new AfricasTalkingGatewayException(e);
}
}
}
/// <summary>
/// Validates SIP address without scheme
/// </summary>
/// <param name="address">
/// This sip Address to validate against
/// </params>
/// <returns>
/// True or false <see cref="bool"/>
/// </returns>
private static bool IsValidSIPAddress(string[] address)
{
bool isValidSIP = true;
foreach (string _address in address)
{
isValidSIP = Regex.Match(_address, @"^(?P<agent>[\w\.]+\@[a-z]\w\.sip\.africastalking\.com)$").Success;
}
return isValidSIP;
}
/// <summary>
/// Checks if the number given is a valid phoneNumber.
/// </summary>
/// <param name="number">
/// Internationally formatted phone number
/// </param>
/// <returns>
/// True or False <see cref="bool"/>.
/// </returns>
private static bool IsPhoneNumber(string[] number)
{
var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance();
bool isValid = false;
foreach (string num in number)
{
var numProto = phoneNumberUtil.Parse(num, null);
isValid = phoneNumberUtil.IsValidNumber(numProto);
}
return isValid;
}
/// <summary>
/// This alllows you to upload media files of type WAV or MP3 to our server
/// The file will live in the server forever
/// </summary>
/// <param name="url">
/// A properly formatted web url.
/// </param>
/// <exception cref="AfricasTalkingGatewayException">
/// Any Exceptions from the gateway
/// </exception>
public dynamic UploadMediaFile(string url, string phoneNumber)
{
var isUrl = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
var isPhoneNumber = IsPhoneNumber(numbers);
if (!(isUrl || isPhoneNumber))
{
throw new AfricasTalkingGatewayException("Malformed Url or Invalid Phone Number");
}
else
{
var data = new Hashtable
{
["username"] = this._username,
["url"] = url,
["phoneNumber"] = phoneNumber
};
var urlString = this.VoiceUrl + "/mediaUpload";
try
{
var response = this.SendPostRequest(data, urlString);
return response;
}
catch (AfricasTalkingGatewayException )
{
throw new AfricasTalkingGatewayException("Failed to upload media file");
}
}
}
/// <summary>
/// The fetch messages method.
/// </summary>
/// <param name="lastReceivedId">
/// The last received id.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by our gateway
/// </exception>
public dynamic FetchMessages(int lastReceivedId)
{
var url = this.BulkSMSUrl + "?username=" + this._username + "&lastReceivedId" + Convert.ToString(lastReceivedId);
var response = this.SendGetRequest(url);
if (this._responseCode != (int)HttpStatusCode.OK)
{
throw new AfricasTalkingGatewayException(response);
}
dynamic json = JObject.Parse(response);
return json["SMSMessageData"]["Messages"];
}
/// <summary>
/// The create subscription method.
/// </summary>
/// <param name="phoneNumber">
/// The phone number.
/// </param>
/// <param name="shortCode">
/// The short code.
/// </param>
/// <param name="keyWord">
/// The key word.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Any error thrown by our gateway class
/// </exception>
public dynamic CreateSubscription(string phoneNumber, string shortCode, string keyWord)
{
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
if (phoneNumber.Length == 0 || shortCode.Length == 0 || keyWord.Length == 0 || !IsPhoneNumber(numbers))
{
throw new AfricasTalkingGatewayException("Some Parameters are missing or not properly formatted");
}
var data = new Hashtable
{
["username"] = this._username,
["phoneNumber"] = phoneNumber,
["shortCode"] = shortCode,
["keyword"] = keyWord
};
var url = this.SubscriptionUrl + "/create";
var response = this.SendPostRequest(data, url);
if (this._responseCode != (int)HttpStatusCode.Created)
{
throw new AfricasTalkingGatewayException(response);
}
dynamic json = JObject.Parse(response);
return json;
}
/// <summary>
/// The delete subscription method.
/// </summary>
/// <param name="phoneNumber">
/// The phone number.
/// </param>
/// <param name="shortCode">
/// The short code.
/// </param>
/// <param name="keyWord">
/// The key word.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by our gateway
/// </exception>
public dynamic DeleteSubscription(string phoneNumber, string shortCode, string keyWord)
{
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
if (phoneNumber.Length == 0 || shortCode.Length == 0 || keyWord.Length == 0 || !IsPhoneNumber(numbers))
{
throw new AfricasTalkingGatewayException("Some Parameters are missing or phonenumber is malformed");
}
else
{
var data = new Hashtable
{
["username"] = this._username,
["phoneNumber"] = phoneNumber,
["shortCode"] = shortCode,
["keyword"] = keyWord
};
var url = this.SubscriptionUrl + "/delete";
var response = this.SendPostRequest(data, url);
if (this._responseCode != (int)HttpStatusCode.Created)
{
throw new AfricasTalkingGatewayException(response);
}
dynamic json = JObject.Parse(response);
return json;
}
}
/// <summary>
/// Initiates an API request to make an outbound voice call.
/// </summary>
/// <param name="from">
/// The registered callerID/ Virtual Number, defaults to Africas's Talking CallerID
/// </param>
/// <param name="to">
/// Caller address, can be a series of SIM numbers in or SIP addresses of the form {agentName/test}.{user}@{countrycode -eg ke/ug/ng}.sip.africastalking.com
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors from our gateway
/// </exception>
public dynamic Call(string from, string to, string requestId)
{
// We do not Validate against phone numbers since it could be a mixture of numbers and sip addresses TBD , very hacky
var dict = new Dictionary<string, string>
{
["username"] = this._username,
["to"] = to,
["from"] = from
};
if (requestId != null)
{
dict["clientRequestId"] = requestId;
}
try
{
var url = VoiceUrl + "/call";
var response = SendPostRequest(dict, url);
dynamic json = JObject.Parse(response);
return json;
}
catch (AfricasTalkingGatewayException e)
{
throw new AfricasTalkingGatewayException(e);
}
}
public dynamic Call(string from, string to) => Call(from, to, requestId: null);
// private static string RawConvert()
/// <summary>
/// Allows one the developer to create a checkout token to be used in a subscription or USSD push.
/// </summary>
/// <param name="phoneNumber">
/// A valid phone number.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
public dynamic CreateCheckoutToken(string phoneNumber)
{
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
if (!IsPhoneNumber(numbers))
{
throw new AfricasTalkingGatewayException("The phone number supplied is not valid");
}
else
{
try
{
var payload = new Hashtable
{
["phoneNumber"] = phoneNumber
};
var response = this.SendPostRequest(payload, this.TokenUrl);
dynamic tokenRes = JObject.Parse(response);
return tokenRes;
}
catch (AfricasTalkingGatewayException e)
{
throw new AfricasTalkingGatewayException("An error ocurred while creating this token: " + e.Message);
}
}
}
/// <summary>
/// Initiates USSD push request.
/// </summary>
/// <param name="phoneNumber">
/// The phone number.
/// </param>
/// <param name="prompt">
/// The prompt.This is the USSD menu to be displayed. Must start with CON or END
/// </param>
/// <param name="checkoutToken">
/// The checkout token.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors from the gateway
/// </exception>
public dynamic InitiateUssdPushRequest(string phoneNumber, string prompt, string checkoutToken)
{
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
if (!IsValidToken(checkoutToken) || prompt.Length == 0 || !IsPhoneNumber(numbers))
{
throw new AfricasTalkingGatewayException("One or some of the arguments supplied are invalid.");
}
try
{
var data = new Hashtable
{
["username"] = this._username,
["phoneNumber"] = phoneNumber,
["menu"] = prompt,
["checkoutToken"] = checkoutToken
};
var apiPath = this.UssdPushUrl;
var response = this.SendPostRequest(data, apiPath);
dynamic res = JObject.Parse(response);
return res;
}
catch (Exception e)
{
throw new AfricasTalkingGatewayException(e.Message + e.StackTrace);
}
}
/// <summary>
/// The get number of queued calls method.
/// </summary>
/// <param name="phoneNumber">
/// The phone number.
/// </param>
/// <param name="queueName">
/// The queue name.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors from our gateway class
/// </exception>
public dynamic GetNumberOfQueuedCalls(string phoneNumber, string queueName)
{
string[] numbers = phoneNumber.Split(separator: new[] {','}, options: StringSplitOptions.RemoveEmptyEntries);
if (!IsPhoneNumber(numbers))
{
throw new AfricasTalkingGatewayException("Phone Number is invalid");
}
{
var data = new Hashtable
{
["username"] = this._username,
["phoneNumbers"] = phoneNumber,
};
if (queueName != null)
{
data["queueName"] = queueName;
}
var url = this.VoiceUrl + "/queueStatus";
var response = this.SendPostRequest(data, url);
dynamic json = JObject.Parse(response);
return json;
}
}
public dynamic GetNumberOfQueuedCalls(string phoneNumber) => GetNumberOfQueuedCalls(phoneNumber, null);
/// <summary>
/// The send airtime method.
/// </summary>
/// <param name="recipients">
/// The recipients.
/// </param>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by our gateway
/// </exception>
public dynamic SendAirtime(dynamic recipients)
{
if (recipients == null)
{
throw new AfricasTalkingGatewayException("Your recepients list is malformed");
}
var urlString = this.AirtimeUrl;
var data = new Hashtable { ["username"] = this._username, ["recipients"] = "[" + recipients + "]" };
try
{
var response = this.SendPostRequest(data, urlString);
if (this._responseCode != (int)HttpStatusCode.Created)
{
throw new AfricasTalkingGatewayException(response);
}
dynamic json = JObject.Parse(response);
return json;
}
catch (AfricasTalkingGatewayException e)
{
throw new AfricasTalkingGatewayException(e);
}
}
/// <summary>
/// The get user data method.
/// </summary>
/// <returns>
/// The <see cref="dynamic"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors thrown by our gateway
/// </exception>
public dynamic GetUserData()
{
var urlString = this.Userdata + "?username=" + this._username;
var response = this.SendGetRequest(urlString);
if (this._responseCode != (int)HttpStatusCode.OK)
{
throw new AfricasTalkingGatewayException(response);
}
dynamic json = JObject.Parse(response);
return json;
}
/// <summary>
/// The card OTP validation url.
/// </summary>
private string CardOtpValidationUrl => this.PaymentsHost + "/card/checkout/validate";
/// <summary>
/// The card checkout url.
/// </summary>
private string CardCheckoutUrl => this.PaymentsHost + "/card/checkout/charge";
/// <summary>
/// The bank checkout url.
/// </summary>
private string BankCheckoutUrl => this.PaymentsHost + "/bank/checkout/charge";
/// <summary>
/// The OTP validation url.
/// </summary>
private string OtpValidationUrl => this.PaymentsHost + "/bank/checkout/validate";
/// <summary>
/// The bank transfer url.
/// </summary>
private string BankTransferUrl => this.PaymentsHost + "/bank/transfer";
/// <summary>
/// Main payments endpoint.
/// </summary>
private string PaymentsUrl => this.PaymentsHost + "/mobile/checkout/request";
/// <summary>
/// Business to Business API endpoint.
/// </summary>
private string B2BPaymentsUrl => this.PaymentsHost + "/mobile/b2b/request";
/// <summary>
/// Business to Client Endpoint.
/// </summary>
private string B2CPaymentsUrl => this.PaymentsHost + "/mobile/b2c/request";
/// <summary>
/// Subscription endpoint.
/// </summary>
private string SubscriptionUrl => this.ApiHost + "/version1/subscription";
/// <summary>
/// The user data endpoint.
/// </summary>
private string Userdata => this.ApiHost + "/version1/user";
/// <summary>
/// Airtime Endpoint.
/// </summary>
private string AirtimeUrl => this.ApiHost + "/version1/airtime/send";
/// <summary>
/// Voice endpoint.
/// </summary>
private string VoiceUrl => (ReferenceEquals(this._environment, "sandbox")
? "https://voice.sandbox.africastalking.com"
: "https://voice.africastalking.com");
/// <summary>
/// Wallet Transfer Endpont
/// </summary>
private string WalletTransferUrl => this.PaymentsHost + "/transfer/wallet";
/// <summary>
/// Topup Stash Endpoint
/// </summary>
private string TopupStashUrl => this.PaymentsHost + "/topup/stash";
/// <summary>
/// SMS Endpoint.
/// </summary>
private string BulkSMSUrl => this.ApiHost + "/version1/messaging";
/// <summary>
/// Find Transaction by ID Endpoint
/// </summary>
private string FindTransactionIdUrl => this.PaymentsHost + "/query/transaction/find";
/// <summary>
/// The Fetch product transactions endpoint
/// </summary>
private string FetchProductTransactionsUrl => this.PaymentsHost + "/query/transaction/fetch";
/// <summary>
/// The Fetch wallet details Endpoint
/// </summary>
private string FetchWalletDetailsUrl => this.PaymentsHost + "/query/wallet/fetch";
/// <summary>
/// Fetch Wallet Balance
/// </summary>
private string FetchWalletBalanceUrl => this.PaymentsHost + "/query/wallet/balance";
/// <summary>
/// Root API host.
/// </summary>
private string ApiHost => (ReferenceEquals(this._environment, "sandbox")
? "https://api.sandbox.africastalking.com"
: "https://api.africastalking.com");
/// <summary>
/// Payment endpoint.
/// </summary>
private string PaymentsHost => (ReferenceEquals(this._environment, "sandbox") ? "https://payments.sandbox.africastalking.com" : "https://payments.africastalking.com");
/// <summary>
/// The token creation url.
/// </summary>
private string TokenUrl => this.ApiHost + "/checkout/token/create";
/// <summary>
/// The USSD push url.
/// </summary>
private string UssdPushUrl => this.ApiHost + "/ussd/push/request";
/// <summary>
/// Premium endpoint.
/// </summary>
private string PremiumSMSURL => (ReferenceEquals(this._environment, "sandbox") ? "https://api.sandbox.africastalking.com/version1/messaging" : "https://content.africastalking.com/version1/messaging");
/// <summary>
/// The send get request helper method.
/// </summary>
/// <param name="urlString">
/// The url string.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors from our gateway class.
/// </exception>
private string SendGetRequest(string urlString)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
var webRequest = (HttpWebRequest)WebRequest.Create(urlString);
webRequest.Method = "GET";
webRequest.Accept = "application/json";
webRequest.Headers.Add("apiKey", this._apikey);
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
this._responseCode = (int)httpResponse.StatusCode;
var webpageReader = new StreamReader(httpResponse.GetResponseStream() ?? throw new InvalidOperationException());
var response = webpageReader.ReadToEnd();
if (this._debug)
{
Console.WriteLine("Full response: " + response);
}
return response;
}
catch (WebException ex)
{
if (ex.Response == null)
{
throw new AfricasTalkingGatewayException(ex.Message);
}
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
var response = reader.ReadToEnd();
if (this._debug)
{
Console.WriteLine("Full response: " + response);
}
return response;
}
}
}
/// <summary>
/// The send post request helper method.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <param name="urlString">
/// The url string.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
/// <exception cref="AfricasTalkingGatewayException">
/// Errors from our gateway class.
/// </exception>
private string SendPostRequest(IDictionary data, string urlString)
{
try
{
var dataStr = string.Empty;
foreach (string key in data.Keys)
{
if (dataStr.Length > 0)
{
dataStr += "&";
}
var value = data[key].ToString();
dataStr += HttpUtility.UrlEncode(key, Encoding.UTF8);
dataStr += "=" + HttpUtility.UrlEncode(value, Encoding.UTF8);
}
var byteArray = Encoding.UTF8.GetBytes(dataStr);
ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
var webRequest = (HttpWebRequest)WebRequest.Create(urlString);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
webRequest.Accept = "application/json";
webRequest.Headers.Add("apiKey", this._apikey);
var webpageStream = webRequest.GetRequestStream();
webpageStream.Write(byteArray, 0, byteArray.Length);
webpageStream.Close();
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
this._responseCode = (int)httpResponse.StatusCode;
var webpageReader = new StreamReader(
httpResponse.GetResponseStream() ?? throw new InvalidOperationException());
var response = webpageReader.ReadToEnd();
if (this._debug)
{
Console.WriteLine("Response: " + response);
}
return response;
}
catch (WebException webException)
{
if (webException.Response == null)
{
throw new AfricasTalkingGatewayException(webException.Message);
}
using (var stream = webException.Response.GetResponseStream())
using (var reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
var response = reader.ReadToEnd();
if (this._debug)
{
Console.WriteLine("Exception: " + response);
}
return response;
}
}
}
/// <summary>
/// Checks if the users supplied a valid currency symbol.
/// </summary>
/// <param name="isoCurrency">
/// The ISO currency.
/// </param>
/// <param name="symbol">
/// The symbol.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private static bool IsValidCurrency(string isoCurrency, out string symbol)
{
symbol = CultureInfo.GetCultures(CultureTypes.AllCultures).Where(c => !c.IsNeutralCulture).Select(
culture =>
{
try
{
return new RegionInfo(culture.LCID);
}
catch
{
return null;
}
}).Where(ri => ri != null && ri.ISOCurrencySymbol == isoCurrency)
.Select(ri => ri.CurrencySymbol)
.FirstOrDefault();
return symbol != null;
}
/// <summary>
/// Checks if the correct transaction ID is supplied.
/// </summary>
/// <param name="transactionId">
/// The transaction ID.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private static bool IsValidTransactionId(string transactionId)
{
return Regex.Match(transactionId, @"^ATPid_.*$").Success && transactionId.Length > 7;
}