Skip to content

Instantly share code, notes, and snippets.

@kitze
Created April 16, 2021 17:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kitze/9c4c55488ac1502a923eebd85aee9896 to your computer and use it in GitHub Desktop.
Save kitze/9c4c55488ac1502a923eebd85aee9896 to your computer and use it in GitHub Desktop.
paddle thingie
//methods
import { BaseSchemaThingie, RawPaddleEvent } from "app/core/paddle/types";
import { filterWebookEvents } from "app/core/paddle/utils/filter-webook-events";
import axios, { AxiosResponse } from "axios";
import { GetPayments } from "./types/getPayments";
import { Schema as GetSubscriptionDetails } from "app/core/paddle/sdk/requests/getSubscriptionDetails/type";
import { GetWebhookEvents, PaddleClientConfig, PaddleRequest } from "./types/types";
export class PaddleSDK {
vendor_id: number;
url: string;
vendor_auth_code: string;
constructor(client: PaddleClientConfig) {
const { url, vendor_id, vendor_auth_code } = client;
this.url = url;
this.vendor_id = vendor_id;
this.vendor_auth_code = vendor_auth_code;
}
request = async <T extends BaseSchemaThingie>(
request: PaddleRequest,
body = {}
): Promise<T["response"] | null> => {
const { url, vendor_id, vendor_auth_code } = this;
let requestUrl = `${url}/${request}`;
let variables = { vendor_id, vendor_auth_code, ...body };
let result: AxiosResponse<T> | undefined;
try {
result = await axios.post(requestUrl, variables);
} catch (err) {
console.log("err", err);
}
if (!result) {
throw new Error("Axios failed");
return null;
}
const { data } = result;
const { response, success, error } = data;
if (success) {
return response;
}
if (error && error?.message) {
// console.log("paddle request error:", error.message);
throw new Error(error.message);
}
throw new Error(`Error!`);
};
async getSubscriptionDetails(args: { subscription_id: number }) {
let results = await this.request<GetSubscriptionDetails>(
PaddleRequest.SubscriptionDetails,
args
);
return results;
}
async getUserPayments(args: { subscription_id: number }): Promise<GetPayments> {
return this.request(PaddleRequest.SubscriptionPayments, args);
}
async getAllWebhookEvents(): Promise<GetWebhookEvents> {
return this.request(PaddleRequest.WebhookEvents);
}
//parsed
async getWebhookEventsForSubscription(args: {
subscription_id: number;
}): Promise<RawPaddleEvent[]> {
const { subscription_id } = args;
const { data } = await this.getAllWebhookEvents();
return filterWebookEvents({ subscription_id, data });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment