52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
|
import * as plugins from './paypal.plugins';
|
||
|
|
||
|
export interface IPayPalOptions {
|
||
|
clientId: string;
|
||
|
clientSecret: string;
|
||
|
}
|
||
|
|
||
|
export class PayPal {
|
||
|
public apiBaseUrl: string = 'https://api.paypal.com'
|
||
|
public options: IPayPalOptions;
|
||
|
|
||
|
private apiToken: string;
|
||
|
private apiTokenExpirationTime: number;
|
||
|
|
||
|
constructor(optionsArg: IPayPalOptions) {
|
||
|
this.options = optionsArg;
|
||
|
}
|
||
|
|
||
|
public async request() {
|
||
|
if (!this.apiToken || this.apiTokenExpirationTime < Date.now()) {
|
||
|
const authHeader = `Basic ${plugins.smartstring.base64.encode(
|
||
|
`${this.options.clientId}:${this.options.clientSecret}`
|
||
|
)}`;
|
||
|
const response = await plugins.smartrequest.request(
|
||
|
`${this.apiBaseUrl}/v1/oauth2/token?grant_type=client_credentials`,
|
||
|
{
|
||
|
method: 'POST',
|
||
|
headers: {
|
||
|
Accept: 'application/json',
|
||
|
'Accept-Language': 'en_US',
|
||
|
Authorization: authHeader,
|
||
|
},
|
||
|
keepAlive: false,
|
||
|
}
|
||
|
);
|
||
|
this.apiToken = response.body.access_token;
|
||
|
this.apiTokenExpirationTime = Date.now() + response.body.expires_in * 1000 - 600000;
|
||
|
}
|
||
|
|
||
|
// we have a token
|
||
|
const response = await plugins.smartrequest.request(`${this.apiBaseUrl}/v1/reporting/transactions?start_date=2020-05-01T00:00:00Z&end_date=2020-05-30T00:00:00Z`, {
|
||
|
method: 'GET',
|
||
|
headers: {
|
||
|
Accept: 'application/json',
|
||
|
'Accept-Language': 'en_US',
|
||
|
Authorization: `Bearer ${this.apiToken}`,
|
||
|
},
|
||
|
});
|
||
|
console.log(response.body);
|
||
|
}
|
||
|
}
|