-
Notifications
You must be signed in to change notification settings - Fork 1
/
AfricasTalkingGateway.go
563 lines (515 loc) · 17.4 KB
/
AfricasTalkingGateway.go
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
//
// Copyright 2017
//By: davidmutia47@gmail.com.
//All rights reserved.
// Use of this source code is governed by a BSD-style
//
/*
AfricasTalking Golang gateway implementation
*/
package AfricasTalkingGateway
import(
"errors"
"io/ioutil"
"net/http"
"encoding/json"
"bytes"
"strconv"
"net/url"
"strings"
"fmt"
)
type AfricasTalking struct{
UserName string
ApiKey string
Environment string
ResponseCode int
}
//Check git desktop is working
func (a AfricasTalking) AfricasTalkingGatewayException(err string) (error) {
return errors.New(err)
}
func AfricasTalkingGateway(username,apikey string,params ...string) (*AfricasTalking){
a:=&AfricasTalking{}
a.ApiKey,a.UserName,a.ResponseCode= apikey,username,0
if len(params) >0{
a.Environment=params[0]
}else{
a.Environment = "production"
}
return a
}
//Parameter for sending message
type MessageParameters struct{
From string
BulkSMSMode int
Enqueue int
Keyword string
LinkId string
RetryDurationInHours string
}
//Function to handle sending messages
func (a AfricasTalking) SendMessage(to,message string,params ...MessageParameters) ([]interface{},error) {
var recipients []interface{}
parameters :=map[string]interface{}{}
parameters["username"],parameters["to"],parameters["message"] = a.UserName,to,message
if len(params)>0{
if params[0].From != ""{
parameters["from"] =params[0].From
}
parameters["bulkSMSMode"] = params[0].BulkSMSMode
parameters["enqueue"] = params[0].Enqueue
if params[0].LinkId !=""{
if linkId,err :=strconv.Atoi(params[0].LinkId);err==nil{
parameters["linkId"] = linkId
}
}
if params[0].RetryDurationInHours !=""{
if retryDurationInHours,err :=strconv.Atoi(params[0].RetryDurationInHours);err==nil{
parameters["retryDurationInHours"] = retryDurationInHours
}
}
}else{
//set defults for bulksmsmode and enqueue parameters
parameters["bulkSMSMode"] = 1
parameters["enqueue"] = 0
}
responseBody,err := a.sendRequest(a.getSmsUrl(),parameters)
if err != nil{
return recipients,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode ==201 {
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return recipients,a.AfricasTalkingGatewayException(err.Error())
}
data :=jsonData.(map[string]interface{})
sMSMessageData := data["SMSMessageData"].(map[string]interface{})
recipients = sMSMessageData["Recipients"].([]interface{})
if len(recipients)>0{
return recipients,nil
}
}
return recipients,a.AfricasTalkingGatewayException(string(responseBody))
}
func (a AfricasTalking) FetchMessages(lastReceivedId int) ([]interface{},error){
var messages []interface{}
//use package url later
urlString := a.getSmsUrl()+"?username="+a.UserName+"&lastReceivedId="+strconv.Itoa(lastReceivedId)
responseBody,err := a.sendRequestGet(urlString)
if err !=nil{
return messages,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode ==200 {
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return messages,a.AfricasTalkingGatewayException(err.Error())
}
data :=jsonData.(map[string]interface{})
sMSMessageData := data["SMSMessageData"].(map[string]interface{})
messages = sMSMessageData["Messages"].([]interface{})
if len(messages)>0{
return messages,nil
}
}
return messages,a.AfricasTalkingGatewayException(string(responseBody))
}
//Subscription methods - creating subscription
func (a AfricasTalking) CreateSubscription(phoneNumber,shortCode,keyword string) (map[string]interface{},error){
urlString := a.getSmsSubscriptionUrl()+"/create"
return a.subscription(urlString,phoneNumber,shortCode,keyword)
}
//Subscription methods - deleting subscription
func (a AfricasTalking) DeleteSubscription(phoneNumber,shortCode,keyword string) (map[string]interface{},error){
urlString := a.getSmsSubscriptionUrl()+"/delete"
return a.subscription(urlString,phoneNumber,shortCode,keyword)
}
//Subscription methods - fetching subscriptions
func (a AfricasTalking) FetchPremiumSubscriptions(shortCode,keyword string, lastReceivedId ...int) ([]interface{},error) {
response :=[]interface{}{}
if shortCode=="" || keyword == "" {
return response,a.AfricasTalkingGatewayException("Supply short code and Keyword")
}
//use package url later
urlString :=a.getSmsSubscriptionUrl()+"?username="+a.UserName+"&shortCode="+shortCode+"&keyword="+keyword+"&lastReceivedId="
if len(lastReceivedId) >0{
urlString += strconv.Itoa(lastReceivedId[0])
}else{
urlString += strconv.Itoa(0)
}
responseBody,err := a.sendRequestGet(urlString)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 200{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
data := jsonData.(map[string]interface{})
subscriptions := data["Subscriptions"].([]interface{})
if len(subscriptions) >0{
return subscriptions,nil
}
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
func (a AfricasTalking) subscription(urlString,phoneNumber,shortCode,keyword string) (map[string]interface{},error){
response :=map[string]interface{}{}
if phoneNumber =="" || shortCode=="" || keyword == "" {
return response,a.AfricasTalkingGatewayException("Supply phone number, short code and Keyword")
}
parameters := map[string]interface{}{}
parameters["username"],parameters["phoneNumber"],parameters["shortCode"],parameters["keyword"] = a.UserName,phoneNumber,shortCode,keyword
responseBody,err := a.sendRequest(urlString,parameters)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
response= jsonData.(map[string]interface{})
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//Voice methods - calling
func (a AfricasTalking) Call(from,to string) (map[string]interface{},error) {
response :=map[string]interface{}{}
parameters := map[string]interface{}{}
parameters["from"],parameters["to"],parameters["username"] = from,to,a.UserName
urlString := a.getVoiceUrl()+"/call"
responseBody,err := a.sendRequest(urlString,parameters)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 200{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error()+"############# json marshal")
}
response= jsonData.(map[string]interface{})
return response,nil
}else{
return response,a.AfricasTalkingGatewayException(string(responseBody)+"########### "+strconv.Itoa(a.ResponseCode))
}
}
func (a AfricasTalking) GetNumQueuedCalls(phoneNumber string,queueName ...string) (map[string]interface{},error){
parameters :=map[string]interface{}{}
response :=map[string]interface{}{}
parameters["username"],parameters["phoneNumber"] = a.UserName,phoneNumber
if len(queueName) >0 {
parameters["queueName"] = queueName[0]
}
urlString := a.getVoiceUrl()+"/queueStatus"
responseBody,err := a.sendRequest(urlString,parameters)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
response= jsonData.(map[string]interface{})
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
func (a AfricasTalking) UploadMediaFile(url string) (map[string]interface{},error) {
response := map[string]interface{}{}
parameters :=map[string]interface{}{}
parameters["username"],parameters["url"] =a.UserName,url
urlString := a.getVoiceUrl()+"/mediaUpload"
responseBody,err := a.sendRequest(urlString,parameters)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
response= jsonData.(map[string]interface{})
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//Airtime methods - buy airtime for a number
func (a AfricasTalking) SendAirtime(params []map[string]interface{}) ([]interface{},error) {
response := []interface{}{}
parameters := map[string]interface{}{}
urlString := a.getAirtimeUrl()+"/send"
parameters["username"] = a.UserName
recipientsJson,_ := json.Marshal(params)
parameters["recipients"] = string(recipientsJson)
responseBody,err := a.sendRequest(urlString,parameters)
if err!=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201{
var jsonData interface{}
err := json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
data := jsonData.(map[string]interface{})
response = data["responses"].([]interface{})
if len(response) >0{
return response,nil
}
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//Payment methods - C2B
func (a AfricasTalking) InitiateMobilePaymentCheckout(productName,phoneNumber,currencyCode string,amount float64,metadata map[string]string) (map[string]string,error){
parameters := map[string]interface{}{}
response := map[string]string{}
parameters["username"],parameters["productName"],parameters["phoneNumber"],parameters["currencyCode"],parameters["amount"],parameters["metadata"] = a.UserName,productName,phoneNumber,currencyCode,amount,metadata
urlString := a.getMobilePaymentCheckoutUrl()
responseBody,err := a.sendJSONRequest(urlString,parameters)
if err !=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201 {
var jsonData interface{}
err = json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
data,ok :=jsonData.(map[string]interface{})
if !ok {
return response,a.AfricasTalkingGatewayException("incorrect response data")
}
if status,ok := data["status"].(string);ok{
response["status"] = status
}
if description,ok := data["description"].(string);ok{
response["description"] = description
}
if transactionId,ok := data["transactionId"].(string);ok{
response["transactionId"] = transactionId
}
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//Payment methods - B2C
func (a AfricasTalking) MobilePaymentB2CRequest(productName string, recipients []map[string]interface{}) ([]interface{},error){
parameters := map[string]interface{}{}
entries := []interface{}{}
parameters["username"],parameters["productName"],parameters["recipients"] = a.UserName,productName,recipients
urlString := a.getMobilePaymentB2CUrl()
responseBody,err := a.sendJSONRequest(urlString,parameters)
if err !=nil {
return entries,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode ==201 {
var jsonData interface{}
err = json.Unmarshal(responseBody,&jsonData)
if err != nil {
return nil,a.AfricasTalkingGatewayException(err.Error())
}
data := jsonData.(map[string]interface{})
entries = data["entries"].([]interface{})
if len(entries)>0 {
return entries,nil
}
}
return entries,a.AfricasTalkingGatewayException(string(responseBody))
}
//Payment methods - B2B
func (a AfricasTalking) MobilePaymentB2BRequest(productName,provider,transferType,currencyCode,destinationChannel string,amount float64,metadata map[string]string,destinationAccount ...string) (map[string]string,error){
parameters :=map[string]interface{}{}
response := map[string]string{}
parameters["username"],parameters["productName"],parameters["provider"],parameters["destinationChannel"],parameters["transferType"],parameters["currencyCode"],parameters["amount"],parameters["metadata"]=a.UserName,productName,provider,destinationChannel,transferType,currencyCode,amount,metadata
if len(destinationAccount) >0{
parameters["destinationChannel"] = destinationChannel[0]
}
urlString:=a.getMobilePaymentB2BUrl()
responseBody,err := a.sendJSONRequest(urlString,parameters)
if err !=nil {
return response,a.AfricasTalkingGatewayException(err.Error())
}
if a.ResponseCode == 201 {
var jsonData interface{}
err = json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
data,ok :=jsonData.(map[string]interface{})
if !ok {
return response,a.AfricasTalkingGatewayException("incorrect response data")
}
if status,ok := data["status"].(string);ok{
response["status"] = status
}
if transactionId,ok := data["transactionId"].(string);ok{
response["transactionId"] = transactionId
}
if transactionFee,ok := data["transactionFee"].(string);ok{
response["transactionFee"] = transactionFee
}
if providerChannel,ok := data["providerChannel"].(string);ok{
response["providerChannel"] = providerChannel
}
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//User data - getting user data eg balance in account
func (a AfricasTalking) GetUserData() (map[string]interface{},error){
response:=map[string]interface{}{}
urlString:= a.getUserDataUrl()+"?username="+a.UserName
responseBody,err := a.sendRequestGet(urlString)
if err!=nil {
}
if a.ResponseCode==200{
var jsonData interface{}
err = json.Unmarshal(responseBody,&jsonData)
if err != nil{
return response,a.AfricasTalkingGatewayException(err.Error())
}
data :=jsonData.(map[string]interface{})
response = data["UserData"].(map[string]interface{})
return response,nil
}
return response,a.AfricasTalkingGatewayException(string(responseBody))
}
//http post request
func (a *AfricasTalking) sendRequest(urlString string,parameters map[string]interface{}) ([]byte,error){
request:= &http.Request{}
var err error
//var data []byte
form := url.Values{}
if len(parameters)!=0{
for key,value := range parameters{
if v,ok := value.(string); ok{
form.Add(key,v)
}else{
if v,ok := value.(int); ok{
form.Add(key,strconv.Itoa(v))
}
}
}
}
fmt.Println(form.Encode())
request,err = http.NewRequest("POST",urlString,strings.NewReader(form.Encode()))
if err !=nil{
return nil,err
}
request.Header.Set("Accept","application/json")
request.Header.Set("Content-Type","application/x-www-form-urlencoded")
request.Header.Set("apikey",a.ApiKey)
client :=&http.Client{}
response,err := client.Do(request)
if err !=nil{
return nil,err
}
defer response.Body.Close()
a.ResponseCode = response.StatusCode
body,err := ioutil.ReadAll(response.Body)
if err !=nil{
return nil,err
}
return body,nil
}
//http get request
func (a *AfricasTalking) sendRequestGet(urlString string) ([]byte,error){
request,err := http.NewRequest("GET",urlString,nil)
if err!=nil{
return nil,err
}
request.Header.Add("Accept", "application/json")
request.Header.Set("apikey",a.ApiKey)
client :=&http.Client{}
response,err := client.Do(request)
if err !=nil{
return nil,err
}
defer response.Body.Close()
a.ResponseCode = response.StatusCode
body,err := ioutil.ReadAll(response.Body)
if err !=nil{
return nil,err
}
return body,nil
}
//json post request
func (a *AfricasTalking) sendJSONRequest(urlString string,parameters map[string]interface{}) ([]byte,error) {
request:= &http.Request{}
var err error
jsonParams,err :=json.Marshal(parameters)
if err !=nil{
return nil,err
}
request,err = http.NewRequest("POST",urlString,bytes.NewBuffer(jsonParams))
if err !=nil{
return nil,err
}
request.Header.Set("Content-Type","application/json")
request.Header.Set("apikey",a.ApiKey)
client :=&http.Client{}
response,err := client.Do(request)
if err !=nil{
return nil,err
}
defer response.Body.Close()
a.ResponseCode = response.StatusCode
body,err := ioutil.ReadAll(response.Body)
if err !=nil{
return nil,err
}
return body,nil
}
func (a AfricasTalking) getApiHost() string{
if a.Environment !="sandbox" {
return "https://api.africastalking.com"
}
return "https://api.sandbox.africastalking.com"
}
func (a AfricasTalking) getPaymentHost() string{
if a.Environment !="sandbox" {
return "https://payments.africastalking.com"
}
return "https://payments.sandbox.africastalking.com"
}
func (a AfricasTalking) getVoiceHost() string{
if a.Environment != "sandbox"{
return "https://voice.africastalking.com"
}
return "https://voice.sandbox.africastalking.com"
}
func (a AfricasTalking) getSmsUrl() (string) {
return a.getApiHost()+"/version1/messaging"
}
func (a AfricasTalking) getMobilePaymentCheckoutUrl() string{
return a.getPaymentHost()+"/mobile/checkout/request"
}
func (a AfricasTalking) getMobilePaymentB2CUrl() string{
return a.getPaymentHost() + "/mobile/b2c/request"
}
func (a AfricasTalking) getMobilePaymentB2BUrl() string{
return a.getPaymentHost() +"/mobile/b2b/request"
}
func (a AfricasTalking) getSmsSubscriptionUrl() string{
return a.getApiHost() + "/version1/subscription"
}
func (a AfricasTalking) getVoiceUrl() string{
return a.getVoiceHost()
}
func (a AfricasTalking) getAirtimeUrl() string{
return a.getApiHost()+"/version1/airtime"
}
func (a AfricasTalking) getUserDataUrl() string{
return a.getApiHost() + "/version1/user"
}