-
Notifications
You must be signed in to change notification settings - Fork 0
/
lipa_na_mpesa.go
68 lines (61 loc) · 2.06 KB
/
lipa_na_mpesa.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
package daraja_wrapper
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const Lipa_na_mpesa_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
type LipaNaMpesaPayStruct struct {
BusinessShortCode, Password, Timestamp string
TransactionType, Amount, PartyA, PartyB string
PhoneNumber, CallBackURL, AccountReference, TransactionDesc string
}
type LipaNaMpesaResp map[string]interface{}
// `LipaNaMpesaPayment` -
// 'Lipa na M-Pesa Online Payment'
// Lipa na M-Pesa Online Payment API is used to initiate a M-Pesa
// transaction on behalf of a customer using STK Push. This is the same technique mySafaricom App
// uses whenever the app is used to make payments.
func (l *LipaNaMpesaPayStruct) LipaNaMpesaPayment(a *Auth, pass_key string) (LipaNaMpesaResp, error) {
l.TransactionType = "CustomerPayBillOnline"
l.GenPasswordAndAssign(pass_key)
var daraja_resp LipaNaMpesaResp
token, err := a.GetAuthKey()
if err != nil {
return daraja_resp, err
}
saf_req, err := json.Marshal(l)
if err != nil {
return daraja_resp, fmt.Errorf("`json.Marshal/1` got the err -> '%s' with args -> '%s'", err, l)
}
url := a.setUrl(Lipa_na_mpesa_url)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(saf_req))
if err != nil {
return daraja_resp, fmt.Errorf("`http.NewRequest/3` got the err -> '%s'.", err)
}
req.Header.Add("Accept", "application/json")
req.Header.Add("content-type", "application/json")
req.Header.Add("Authorization", "Bearer "+token.Token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return daraja_resp, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return daraja_resp, err
}
err = json.Unmarshal(body, &daraja_resp)
if err != nil {
return daraja_resp, err
}
return daraja_resp, nil
}
func (l *LipaNaMpesaPayStruct) GenPasswordAndAssign(pass_key string) {
var msg string = l.BusinessShortCode + pass_key + l.Timestamp
l.Password = string(base64.StdEncoding.EncodeToString([]byte(msg)))
}