-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZarinpal.js
324 lines (279 loc) · 7.81 KB
/
Zarinpal.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
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
const { Headers, default: fetch } = require("node-fetch")
const ERRORS = require("./enums/ERRORS.json")
const {
checkAmount,
checkCallbackURL,
checkDescription,
isTypeNumber,
isTypeString,
checkAuthority,
} = require("./utils")
class Zarinpal {
/**
*
* @param {string} merchantID A string with **`36`** chracters, get this code from *Zarinpal website*
* @param {boolean} sandbox currently **`sandbox`** mode is **`disabled`** by Zarinpal
*/
constructor(merchantID, sandbox = false) {
if (!isTypeString(merchantID)) {
throw new Error(":: ARGUMENT ERROR merchantID should be of type string")
}
if (merchantID.length !== 36) {
throw new Error(":: ARGUMENT ERROR merchantID should be 36 characters long")
}
if (!!sandbox) {
throw new Error(":: Zarinpal has disabled the sandbox mode you cannot use that until they enable it gain")
}
this.sandbox = !!sandbox
this.merchantID = merchantID
}
/**
* #### Create a new payment request(`transaction`)
* @param {{
* amount: Long,
* description: string,
* callback_url: string,
* metadata?: {mobile: string, email: string}
* mobile?: string,
* email?: string
* currency?: "IRT"|"IRR"
* }} argument
*/
async paymentRequest({
amount,
description,
callback_url,
metadata,
mobile,
email,
currency = "IRT" // it also can be "IRR"
}) {
const url = this.sandbox ? "https://sandbox.zarinpal.com/pg/v4/payment/request.json"
:
"https://api.zarinpal.com/pg/v4/payment/request.json"
const amountValidity = checkAmount(amount)
if (!amountValidity.status) {
throw new Error(amountValidity.reason)
}
const descriptionValidity = checkDescription(description)
if (!descriptionValidity.status) {
throw new Error(descriptionValidity.reason)
}
const callback_urlValidity = checkCallbackURL(callback_url)
if (!callback_urlValidity.status) {
throw new Error(callback_urlValidity.reason)
}
if (currency !== "IRR" && currency !== "IRT") {
throw new Error("Currency is not valid it can be either 'IRR' for rial or 'IRT' for toman, currency" + currency)
}
const data = {
merchant_id: this.merchantID,
amount,
description,
currency,
callback_url,
metadata,
mobile,
email,
}
return this.#send(url, data);
}
async #send(url, data) {
const headers = new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
});
try {
const response = await fetch(url, {
method: 'post',
body: JSON.stringify(data),
headers,
});
// console.log("response is", response)
return await response.json()
} catch (e) {
console.log("::ERROR while trying to send", url, data, e)
}
}
/**
*
* @param paymentRequest
* ```js
* const paymentRequest = await zarin.paymentRequest({...})
* ```
*/
wasSuccessfull(paymentRequest) {
return paymentRequest?.data?.code === 100
}
/**
* #### Authority is the code you get when the paymentRequest is successfull
* @param paymentRequest
* ```js
* const paymentRequest = await zarin.paymentRequest({...})
* ```
*/
getAuthority(paymentRequest) {
return paymentRequest?.data?.authority
}
/**
* #### Redirect user to this URL for payment
* @param paymentRequest
* ```js
* const paymentRequest = await zarin.paymentRequest({...})
* ```
*/
getRedirectURL(paymentRequest) {
if (!this.wasSuccessfull(paymentRequest)) return ""
const authority = this.getAuthority(paymentRequest)
return this.sandbox ?
`https://sandbox.zarinpal.com/pg/StartPay/${authority}`
:
`https://www.zarinpal.com/pg/StartPay/${authority}`
}
/**
*
* @param {{Status: "OK"|"NOK"}} query
* @deprecated use **`didUserPaySuccessfully`** method instead
* > `Note:` this method will get deleted in the next version use `didUserPaySuccessfully` method instead
*/
didUserPayedSuccessfully(query) {
return query && query.Status === "OK"
}
/**
*
* @param {{Status: "OK"|"NOK"}} query
*/
didUserPaySuccessfully(query) {
return query && query.Status === "OK"
}
/**
*
* @param {{Authority: string}} query
*/
getAuthorityAfterSuccessfullPayment(query) {
return query && query.Authority
}
/**
* #### Verify the payment in your api route(`callback_url`)
*
* @param {{
* amount: Long
* authority: string
* }} argument
*
* `Note:` If you dont verify a payment zarinpal will return the user's money after a certain period
*
*/
async verifyPayment({
amount,
authority,
}) {
const url = this.sandbox ?
"https://sandbox.zarinpal.com/pg/v4/payment/verify.json"
:
"https://api.zarinpal.com/pg/v4/payment/verify.json"
const amountValidity = checkAmount(amount)
if (!amountValidity.status) {
throw new Error(amountValidity.reason)
}
const authorityValidity = checkAuthority(authority)
if (!authorityValidity.status) {
throw new Error(authorityValidity.reason)
}
const data = {
merchant_id: this.merchantID,
amount,
authority,
}
return this.#send(url, data);
}
/**
* #### Find out if verification was successfull
* @param verifyResponse
* ```js
* const verifyResponse = await zarin.verifyPayment({...})
* ```
*/
wasVerifySuccessfull(verifyResponse) {
return (
verifyResponse?.data?.code === 100 ||
// code 101 means that this is the second time we are verifying this successfull payment
verifyResponse?.data?.code === 101
)
}
/**
* #### Get masked card number `ex: 5434-****-****-3215`
* @param verifyResponse
* ```js
* const verifyResponse = await zarin.verifyPayment({...})
* ```
*/
getMaskedCardPan(verifyResponse) {
return verifyResponse?.data?.card_pan
}
/**
* #### Get reference id of payment `ex: 23453135`
* @param verifyResponse
* ```js
* const verifyResponse = await zarin.verifyPayment({...})
* ```
*/
getRefID(verifyResponse) {
return verifyResponse?.data?.ref_id
}
/**
* #### Get the fee that you/customer has payed for the payment amount `ex: 3000`
* @param verifyResponse
* ```js
* const verifyResponse = await zarin.verifyPayment({...})
* ```
*/
getFee(verifyResponse) {
return verifyResponse?.data?.fee
}
/**
* #### Returns a list of previous unverified requests
*/
async getAllUnverifiedRequests() {
const url = "https://api.zarinpal.com/pg/v4/payment/unVerified.json"
const data = {
merchant_id: this.merchantID,
}
return this.#send(url, data);
}
/**
* #### translates error to farsi if its a predefined error
* @param response
* ```js
* const response = await zarin.paymentRequest({...})
* ```
* for list of predefined error please check https://www.zarinpal.com/docs/md/paymentGateway/errorList.html
*/
translateError(response) {
const errorCode = response?.errors?.code
if (!isTypeNumber(errorCode)) return ""
const maybeFarsiErrorMessage = ERRORS[errorCode.toString()]
return maybeFarsiErrorMessage ?? ""
}
/**
* @param {{authority: string}} argument
* ##### `NOTE:` for using refund you should first request an access token
* from zarinpal website
* ##### *This method is not tested yet*
*/
async refund({
authority,
}) {
const url = "https://api.zarinpal.com/pg/v4/payment/refund.json"
const authorityValidity = checkAuthority(authority)
if (!authorityValidity.status) {
throw new Error(authorityValidity.reason)
}
const data = {
merchant_id: this.merchantID,
authority,
}
return this.#send(url, data);
}
}
module.exports = Zarinpal