forked from vernu/telebirrjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telebirr.js
101 lines (89 loc) · 2.44 KB
/
telebirr.js
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
const crypto = require('crypto')
const NodeRSA = require('node-rsa')
const axios = require('axios')
const TELEBIRR_H5_URL =
'https://app.ethiomobilemoney.et:2121/ammapi/payment/service-openup/toTradeWebPay'
const TELEBIRR_IN_APP_URL =
'https://app.ethiomobilemoney.et:2121/ammapi/payment/service-openup/toTradeMobilePay'
class Telebirr {
constructor({ appId, appKey, shortCode, publicKey }) {
this.appId = appId
this.appKey = appKey
this.shortCode = shortCode
this.publicKey = publicKey
}
async makePayment({
paymentMethod = 'web',
nonce,
notifyUrl,
totalAmount,
outTradeNo,
receiveName,
returnApp='com.example.app',
returnUrl,
subject,
timeoutExpress = `${24 * 60}`, // 1 day
}) {
const params = {
appId: this.appId,
appKey: this.appKey,
nonce,
notifyUrl,
outTradeNo,
receiveName,
returnApp,
returnUrl,
shortCode: this.shortCode,
subject,
timeoutExpress,
timestamp: new Date().getTime(),
totalAmount,
}
const url = paymentMethod == 'app' ? TELEBIRR_IN_APP_URL : TELEBIRR_H5_URL
const payload = {
appid: this.appId,
sign: this.signData(params),
ussd: this.encrypt(params),
}
try {
const res = await axios.post(url, payload)
return { success: res.data.code == 200, response: res.data }
} catch (e) {
console.log(e)
return { success: false, error: e }
}
}
encrypt(payload) {
const rsaKey = new NodeRSA(
`-----BEGIN PUBLIC KEY-----\n${this.publicKey}\n-----END PUBLIC KEY-----`,
'public',
{
encryptionScheme: 'pkcs1',
}
)
const dataToEncrypt = Buffer.from(JSON.stringify(payload))
return rsaKey.encrypt(dataToEncrypt, 'base64', 'utf8')
}
signData(fields) {
const encodedFields = Object.keys(fields)
.sort()
.map((key) => `${key}=${fields[key]}`)
.join('&')
return crypto.createHash('sha256').update(encodedFields).digest('hex')
}
decryptPublic(dataToDecrypt) {
const rsaKey = new NodeRSA(
`-----BEGIN PUBLIC KEY-----\n${this.publicKey}\n-----END PUBLIC KEY-----`,
'public',
{
encryptionScheme: 'pkcs1',
}
)
return rsaKey.decryptPublic(dataToDecrypt, 'utf8')
}
getDecryptedCallbackNotification(encryptedText) {
const decryptedText = this.decryptPublic(encryptedText)
return JSON.parse(decryptedText)
}
}
module.exports = Telebirr