This repository has been archived by the owner on Jul 14, 2022. It is now read-only.
/
braintree.ts
66 lines (60 loc) · 1.7 KB
/
braintree.ts
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
import * as braintree from "braintree-web";
export interface PaymentData {
lastDigits: string;
ccType: string;
token: string;
}
export interface ICardInputs {
ccCsc: string;
ccExp: string;
ccNumber: string;
}
export type CardError = { field?: string; message: string } | null;
export interface ICardErrors {
cvv: CardError;
expirationMonth: CardError;
expirationYear: CardError;
number: CardError;
}
export interface ErrorData {
fieldErrors: ICardErrors;
nonFieldError?: string;
}
export interface IPaymentCardError {
code: string;
field: string;
message: string;
}
export const braintreePayment = (paymentClientToken: string, creditCard: any) =>
new Promise<PaymentData | ErrorData[]>((resolve, reject) => {
braintree.client.create(
{
authorization: paymentClientToken,
},
(_err, client) => {
client.request(
{
data: { creditCard },
endpoint: "payment_methods/credit_cards",
method: "post",
},
(error: any, response: any) => {
if (error) {
if (error.details.originalError.fieldErrors.length > 0) {
error.details.originalError.fieldErrors.map((error: any) => {
if (error.field === "creditCard") {
reject(error.fieldErrors);
}
});
}
} else {
const lastDigits = response.creditCards[0].details.lastFour;
const ccType = response.creditCards[0].details.cardType;
const token = response.creditCards[0].nonce;
resolve({ lastDigits, ccType, token });
}
}
);
}
);
});