@lomray/microservice-payment-stripe
Version:
Stripe payment microservice based on NodeJS & inverted json.
395 lines (394 loc) • 13.5 kB
TypeScript
import StripeSdk from 'stripe';
import { EntityManager } from 'typeorm';
import BalanceType from "../../constants/balance-type.js";
import BusinessType from "../../constants/business-type.js";
import PayoutMethodType from "../../constants/payout-method-type.js";
import StripeAccountTypes from "../../constants/stripe-account-types.js";
import TransactionRole from "../../constants/transaction-role.js";
import BankAccount from "../../entities/bank-account.js";
import Card from "../../entities/card.js";
import Coupon from "../../entities/coupon.js";
import Customer from "../../entities/customer.js";
import Price from "../../entities/price.js";
import Product from "../../entities/product.js";
import Transaction from "../../entities/transaction.js";
import TBalance from "../../interfaces/balance.js";
import TCurrency from "../../interfaces/currency.js";
import Abstract from "./abstract.js";
import { IBankAccountParams, ICardParams, ICouponParams, IPriceParams, IProductParams } from "./abstract.js";
interface IStripeProductParams extends IProductParams {
name: string;
description?: string;
images?: string[];
}
type TAvailablePaymentMethods = StripeSdk.Card.AvailablePayoutMethod[] | StripeSdk.BankAccount.AvailablePayoutMethod[] | null;
type TCustomerBalance = Record<BalanceType, TBalance>;
interface IInstantPayoutParams {
userId: string;
amount: number;
entityId?: string;
payoutMethod?: IPayoutMethod;
currency?: TCurrency;
}
interface IPaymentIntentParams {
userId: string;
receiverId: string;
entityCost: number;
feesPayer?: TransactionRole;
cardId?: string;
title?: string;
applicationPaymentPercent?: number;
entityId?: string;
additionalFeesPercent?: Record<TransactionRole, number>;
extraReceiverRevenuePercent?: number;
withTax?: boolean;
}
interface ICheckoutParams {
priceId: string;
userId: string;
successUrl: string;
cancelUrl: string;
isAllowPromoCode?: boolean;
}
interface ITransferInfo {
amount: number;
destinationUser: string;
userId: string;
}
interface IPayoutMethod {
id: string;
method: PayoutMethodType;
}
interface ICheckoutCart {
redirectUrl: string | null;
clientSecret: string | null;
}
type TCardData = StripeSdk.PaymentMethodCreateParams.Card1 | StripeSdk.PaymentMethodCreateParams.Card2;
interface IStripeCouponParams extends ICouponParams {
currency?: TCurrency;
}
interface IStripePromoCodeParams {
couponId: string;
code?: string;
maxRedemptions?: number;
}
interface ICreateMultipleProductCheckout {
cartId: string;
userId: string;
customerEmail?: string;
isEmbeddedMode?: boolean;
}
interface ICreateMultipleProductCheckoutEmbedded extends ICreateMultipleProductCheckout {
isEmbeddedMode: true;
returnUrl: string | null;
}
interface ICreateMultipleProductCheckoutStripeHosted extends ICreateMultipleProductCheckout {
isEmbeddedMode: false;
successUrl: string;
cancelUrl: string;
}
type TCreateMultipleProductCheckoutParams = ICreateMultipleProductCheckoutEmbedded | ICreateMultipleProductCheckoutStripeHosted;
/**
* Stripe payment provider
*/
declare class Stripe extends Abstract {
/**
* Init service
*/
/**
* Init service
*/
static init(manager?: EntityManager): Promise<Stripe>;
/**
* Add new card
* @description Definitions:
* 1. Usage example - only in integration tests
* 2. Use setup intent for live-mode
* 3. For creating card manually with the sensitive data such as digits, cvc. Platform
* account must be eligible for PCI (Payment Card Industry Data Security Standards)
*/
/**
* Add new card
* @description Definitions:
* 1. Usage example - only in integration tests
* 2. Use setup intent for live-mode
* 3. For creating card manually with the sensitive data such as digits, cvc. Platform
* account must be eligible for PCI (Payment Card Industry Data Security Standards)
*/
addCard(params: ICardParams): Promise<Card>;
/**
* Add bank account
* @description Usage example - integration tests
* @TODO: Integrate with stripe
*/
/**
* Add bank account
* @description Usage example - integration tests
* @TODO: Integrate with stripe
*/
addBankAccount({ bankAccountId, ...rest }: IBankAccountParams): Promise<BankAccount>;
/**
* Create SetupIntent and return to client secret
* @description Use on session usage for checkouts
*/
/**
* Create SetupIntent and return to client secret
* @description Use on session usage for checkouts
*/
setupIntent(userId: string): Promise<string | null>;
/**
* Create Customer entity
*/
/**
* Create Customer entity
*/
createCustomer(userId: string, email?: string, name?: string): Promise<Customer>;
/**
* Remove Customer from db and stripe
* @description Usage example - integration tests
*/
/**
* Remove Customer from db and stripe
* @description Usage example - integration tests
*/
removeCustomer(userId: string): Promise<boolean>;
/**
* Create Product entity
*/
/**
* Create Product entity
*/
createProduct(params: IStripeProductParams): Promise<Product>;
/**
* Create Price entity
*/
/**
* Create Price entity
*/
createPrice(params: IPriceParams): Promise<Price>;
/**
* Create checkout session and return url to redirect user for payment
*/
/**
* Create checkout session and return url to redirect user for payment
*/
createCheckout(params: ICheckoutParams): Promise<string | null>;
/**
* Create checkout session for existing cart and return url to redirect user for payment
* @TODO: get rid of the ts-ignores
*/
/**
* Create checkout session for existing cart and return url to redirect user for payment
* @TODO: get rid of the ts-ignores
*/
createCartCheckout(params: TCreateMultipleProductCheckoutParams): Promise<ICheckoutCart | null>;
/**
* Connect account
* @description Create ConnectAccount make redirect to account link and save stripeConnectAccount in customer
*/
/**
* Connect account
* @description Create ConnectAccount make redirect to account link and save stripeConnectAccount in customer
*/
connectAccount(userId: string, email: string, accountType: StripeAccountTypes, refreshUrl: string, returnUrl: string, businessType?: BusinessType): Promise<string>;
/**
* Returns dashboard login link
* @description Eligible only for the express connect accounts.
* DO NOT email, text, or otherwise send login link URLs directly to user
*/
/**
* Returns dashboard login link
* @description Eligible only for the express connect accounts.
* DO NOT email, text, or otherwise send login link URLs directly to user
*/
getDashboardLoginLink(userId: string): Promise<string>;
/**
* Returns account link
* @description Use when user needs to update connect account data
*/
/**
* Returns account link
* @description Use when user needs to update connect account data
*/
getConnectAccountLink(userId: string, refreshUrl: string, returnUrl: string): Promise<string>;
/**
* Get the webhook from stripe and handle deciding on type of event
* @description If handlers can be used for connect and master account - wrap it in handlers callbacks
*/
/**
* Get the webhook from stripe and handle deciding on type of event
* @description If handlers can be used for connect and master account - wrap it in handlers callbacks
*/
handleWebhookEvent(payload: string, signature: string, webhookKey: string, webhookType: string): Promise<void>;
/**
* Create instant payout
* @description Should be called from the API
*/
/**
* Create instant payout
* @description Should be called from the API
*/
instantPayout({ userId, amount, entityId, payoutMethod, currency, }: IInstantPayoutParams): Promise<boolean>;
/**
* Returns user related connect account balance
*/
/**
* Returns user related connect account balance
*/
getBalance(userId: string): Promise<TCustomerBalance>;
/**
* Handles completing of transaction inside stripe payment process
*/
/**
* Handles completing of transaction inside stripe payment process
*/
handleTransactionCompleted(event: StripeSdk.Event): Promise<Transaction | void>;
/**
* Create transfer for connected account
*/
/**
* Create transfer for connected account
*/
createTransfer(entityId: string, userId: string, payoutCoeff: number): Promise<void>;
/**
* Attach to transactions charge refs (transfer, destination payment and related amounts)
*/
/**
* Attach to transactions charge refs (transfer, destination payment and related amounts)
*/
attachToTransactionsChargeRefs(chargeId: string): Promise<void>;
/**
* Create PaymentIntent
*/
/**
* Create PaymentIntent
*/
createPaymentIntent({ userId, entityCost, receiverId, cardId, title, applicationPaymentPercent, entityId, additionalFeesPercent, extraReceiverRevenuePercent, withTax, feesPayer, }: IPaymentIntentParams): Promise<[Transaction, Transaction]>;
/**
* Creates payout transfers for given entities
*/
/**
* Creates payout transfers for given entities
*/
payout(entitiesIds: {
id: string;
userId: string;
}[]): Promise<boolean>;
/**
* Set default customer payment method
*/
/**
* Set default customer payment method
*/
setDefaultCustomerPaymentMethod(customerId: string, paymentMethodId: string): Promise<boolean>;
/**
* Set default customer payment method
*/
/**
* Set default customer payment method
*/
removeCustomerPaymentMethod(paymentMethodId: string): Promise<boolean>;
/**
* Create stripe promo code
*/
/**
* Create stripe promo code
*/
createPromoCode({ couponId, code: userCode, maxRedemptions, }: IStripePromoCodeParams): Promise<{
id: string;
code: string;
}>;
/**
* Remove stripe coupon
*/
/**
* Remove stripe coupon
*/
removeCoupon(couponId: string): Promise<boolean>;
/**
* Create stripe coupon
*/
/**
* Create stripe coupon
*/
createCoupon({ userId, name, currency, products, percentOff, amountOff, maxRedemptions, duration, durationInMonths, }: IStripeCouponParams): Promise<Coupon>;
/**
* Get and validate receiver and sender
*/
/**
* Get and validate receiver and sender
*/
protected getAndValidateTransactionContributors(senderId: string, receiverId: string): Promise<{
receiver: Customer;
sender: Customer;
}>;
/**
* Returns payout method data
*/
/**
* Returns payout method data
*/
protected getPayoutMethodAllowances(userId: string, payoutMethod?: IPayoutMethod): Promise<{
externalAccountId: string;
isInstantPayoutAllowed: boolean;
} | undefined>;
/**
* Returns card for charging payment
*/
/**
* Returns card for charging payment
*/
protected getChargingCard(userId: string, cardId?: string): Promise<Card>;
/**
* Returns account link
*/
/**
* Returns account link
*/
protected buildAccountLink(accountId: string, refreshUrl: string, returnUrl: string): Promise<StripeSdk.AccountLink>;
/**
* Build card data
*/
/**
* Build card data
*/
protected static buildCardData({ cvc, expired, digits, token, }: ICardParams): TCardData | undefined;
/**
* Check if transfer is object
*/
/**
* Check if transfer is object
*/
protected static checkIfApplicationFeeIsObject(applicationFee?: StripeSdk.ApplicationFee | string | null): applicationFee is StripeSdk.ApplicationFee;
/**
* Get and calculate transfer information
*/
/**
* Get and calculate transfer information
*/
protected getTransferInfo(entityId: string, userId: string): Promise<ITransferInfo | undefined>;
/**
* Process webhook event
* @TODO: make this extendable
*/
/**
* Process webhook event
* @TODO: make this extendable
*/
protected processWebhookEvent(event: StripeSdk.Event, webhookType: string): Promise<void>;
/**
* Validate and transform coupon duration input
*/
/**
* Validate and transform coupon duration input
*/
protected static validateAndTransformCouponDurationInput({ duration, durationInMonths, }: Pick<IStripeCouponParams, 'duration' | 'durationInMonths'>): Pick<StripeSdk.CouponCreateParams, 'duration' | 'duration_in_months'>;
/**
* Validate and transform coupon discount input
*/
/**
* Validate and transform coupon discount input
*/
protected static validateAndTransformCouponDiscountInput({ percentOff, amountOff, }: Pick<IStripeCouponParams, 'percentOff' | 'amountOff'>): Pick<StripeSdk.CouponCreateParams, 'amount_off' | 'percent_off'>;
}
export { Stripe as default, IStripeProductParams, TAvailablePaymentMethods, TCustomerBalance, IInstantPayoutParams, IPaymentIntentParams };