Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@smartpay/sdk-node

Package Overview
Dependencies
Maintainers
3
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@smartpay/sdk-node - npm Package Compare versions

Comparing version 0.6.0 to 0.7.0

build/cjs/Smartpay/base.d.ts

2

build/cjs/index.d.ts

@@ -1,3 +0,3 @@

import Smartpay from './smartpay';
import Smartpay from './Smartpay';
export { isValidCheckoutSessionId, isValidOrderId, isValidPaymentId, } from './utils';
export default Smartpay;

@@ -111,7 +111,8 @@ import type { CustomerInfo, CustomerInfoLoose, SimpleLineItem, SimpleChekoutSessionPayload, ShippingInfo, Address } from './types';

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};

@@ -160,9 +161,10 @@ declare const _default: {

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};
};
export default _default;

@@ -1,2 +0,4 @@

import { KeyString, SmartPayOptions, CheckoutSession, SimpleChekoutSessionPayload, Payment, Refund, Order, GetOrdersParams, GetOrderParams, CancelOrderParams, CreatePaymentParams, GetPaymentParams, CreateRefundParams, GetRefundParams, OrdersCollection } from './types';
/// <reference types="node" />
import { Request, Response } from 'express';
import { KeyString, SmartPayOptions, CheckoutSession, SimpleChekoutSessionPayload, Payment, Refund, Order, GetOrdersParams, GetOrderParams, CancelOrderParams, CreatePaymentParams, GetPaymentParams, CreateRefundParams, GetRefundParams, OrdersCollection, CalculateWebhookSignatureParams, VerifyWebhookSignatureParams } from './types';
interface Params {

@@ -45,4 +47,8 @@ [key: string]: string | number;

setPublicKey(publicKey: KeyString): {};
static getSessionUrl(session: CheckoutSession, options?: GetSessionURLOptions): string;
static getSessionURL(session: CheckoutSession, options?: GetSessionURLOptions): string;
static calculateWebhookSignature(params: CalculateWebhookSignatureParams): string;
static verifyWebhookSignature(params: VerifyWebhookSignatureParams): boolean;
static expressWebhookMiddleware(secret: string | Function): (req: Request, res: Response, buf: Buffer) => void;
}
export default Smartpay;

@@ -135,7 +135,8 @@ export interface LooseObject {

customerInfo?: CustomerInfo;
locale?: string;
successUrl?: string;
cancelUrl?: string;
description?: string;
metadata?: MetaData;
reference?: string;
successUrl?: string;
cancelUrl?: string;
promotionCode?: string;

@@ -236,2 +237,50 @@ idempotencyKey?: string;

};
export declare type WebhookEndpoint = {
id: string;
object: string;
active: boolean;
createdAt: number;
description?: string;
eventSubscriptions: string[];
metadata?: MetaData;
test: boolean;
url: string;
updatedAt: number;
};
export declare type Coupon = {
id: string;
object: string;
active: boolean;
name: string;
createdAt: number;
currency?: string;
description?: string;
discountAmount?: number;
discountPercentage?: number;
discountType: string;
expiresAt?: number;
maxRedemptionCount?: number;
redemptionCount: number;
sponsored: boolean;
metadata?: MetaData;
test: boolean;
updatedAt: number;
};
export declare type PromotionCode = {
id: string;
object: string;
active: boolean;
code: string;
createdAt: number;
currency?: string;
expiresAt?: number;
firstTimeTransaction: boolean;
onePerCustomer: boolean;
maxRedemptionCount?: number;
redemptionCount: number;
minimumAmount?: number;
metadata?: MetaData;
test: boolean;
updatedAt: number;
};
export declare type JTDError = {

@@ -241,3 +290,3 @@ instancePath: string[];

};
export declare type GetOrdersParams = {
export declare type ListParams = {
expand?: string;

@@ -247,14 +296,6 @@ pageToken?: string;

};
export declare type GetOrderParams = {
export declare type GetObjectParams = {
id?: string;
expand?: string;
};
export declare type GetPaymentParams = {
id?: string;
expand?: string;
};
export declare type GetRefundParams = {
id?: string;
expand?: string;
};
export declare type CancelOrderParams = {

@@ -274,2 +315,8 @@ id?: string;

};
export declare type UpdatePaymentParams = {
id?: string;
reference?: string;
description?: string;
metadata?: MetaData;
};
export declare type CreateRefundParams = {

@@ -285,3 +332,61 @@ payment?: string;

};
export declare type OrdersCollection = {
export declare type UpdateRefundParams = {
id?: string;
reference?: string;
description?: string;
metadata?: MetaData;
};
export declare type CreateWebhookEndpointParams = {
url?: string;
description?: string;
eventSubscriptions?: string[];
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdateWebhookEndpointParams = CreateWebhookEndpointParams & {
id?: string;
active?: boolean;
};
export declare type CreateCouponParams = {
name?: string;
currency?: string;
description?: string;
discountAmount?: number;
discountPercentage?: number;
discountType?: string;
expiresAt?: number;
maxRedemptionCount?: number;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdateCouponParams = {
id?: string;
active?: boolean;
name?: string;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type CreatePromotionCodeParams = {
active?: boolean;
code?: string;
coupon?: string;
currency?: string;
expiresAt?: number;
firstTimeTransaction?: boolean;
onePerCustomer?: boolean;
maxRedemptionCount?: number;
minimumAmount?: number;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdatePromotionCodeParams = {
id?: string;
active?: boolean;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type DeleteObjectParams = {
id?: string;
};
export declare type Collection<T> = {
object: string;

@@ -292,6 +397,13 @@ pageToken: string;

results: number;
data: Array<Order>;
data: Array<T>;
};
export declare type CalculateWebhookSignatureParams = {
data: string;
secret: string;
};
export declare type VerifyWebhookSignatureParams = CalculateWebhookSignatureParams & {
signature: string;
};
export declare type ErrorDetail = any;
export declare type ErrorDetails = ErrorDetail[];
export {};

@@ -19,2 +19,5 @@ import type { KeyString, SimpleChekoutSessionPayload, ErrorDetails, LooseObject } from './types';

export declare const isValidRefundId: (input: string) => boolean;
export declare const isValidWebhookEndpointId: (input: string) => boolean;
export declare const isValidCouponId: (input: string) => boolean;
export declare const isValidPromotionCodeId: (input: string) => boolean;
export declare const validateCheckoutSessionPayload: (payload: SimpleChekoutSessionPayload) => ErrorDetails;

@@ -66,7 +69,8 @@ /**

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};

@@ -73,0 +77,0 @@ export declare const omit: (obj: LooseObject, omitKeys: string[]) => {

@@ -1,3 +0,3 @@

import Smartpay from './smartpay';
import Smartpay from './Smartpay';
export { isValidCheckoutSessionId, isValidOrderId, isValidPaymentId, } from './utils';
export default Smartpay;

@@ -21,3 +21,3 @@ var __defProp = Object.defineProperty;

// src/smartpay.ts
// src/Smartpay/base.ts
import fetchRetry from "fetch-retry";

@@ -194,7 +194,8 @@ import originalFetch from "isomorphic-unfetch";

shippingInfo,
locale,
successUrl,
cancelUrl,
reference,
description,
metadata,
successUrl,
cancelUrl
metadata
} = payload;

@@ -208,7 +209,8 @@ const rest = omit(payload, [

"shippingInfo",
"locale",
"successUrl",
"cancelUrl",
"reference",
"metadata",
"description",
"successUrl",
"cancelUrl"
"description"
]);

@@ -222,7 +224,8 @@ return __spreadProps(__spreadValues({}, rest), {

shippingInfo: normalizeShippingInfo(shippingInfo),
locale,
successUrl,
cancelUrl,
reference,
description,
metadata,
successUrl,
cancelUrl
metadata
});

@@ -324,2 +327,5 @@ };

var refundIdRegExp = /^refund_(test|live)_[0-9a-zA-Z]+$/;
var webhookEndpointIdRegExp = /^webhookendpoint_(test|live)_[0-9a-zA-Z]+$/;
var couponIdRegExp = /^coupon_(test|live)_[0-9a-zA-Z]+$/;
var promotionCodeIdRegExp = /^promotioncode_(test|live)_[0-9a-zA-Z]+$/;
var SmartpayError = class extends Error {

@@ -358,2 +364,11 @@ constructor({

};
var isValidWebhookEndpointId = (input) => {
return webhookEndpointIdRegExp.test(input);
};
var isValidCouponId = (input) => {
return couponIdRegExp.test(input);
};
var isValidPromotionCodeId = (input) => {
return promotionCodeIdRegExp.test(input);
};
var validateCheckoutSessionPayload = (payload) => {

@@ -421,3 +436,3 @@ const errors = validate(simple_checkout_session_payload_jtd_default, JSON.parse(JSON.stringify(payload)));

// src/smartpay.ts
// src/Smartpay/base.ts
var fetch = fetchRetry(originalFetch, {

@@ -431,10 +446,10 @@ retries: 1,

var API_PREFIX = "https://api.smartpay.co/v1";
var CHECKOUT_URL = "https://checkout.smartpay.co";
var GET = "GET";
var POST = "POST";
var PUT = "PUT";
var PATCH = "PATCH";
var DELETE = "DELETE";
var _a, _b;
var SMARTPAY_API_PREFIX = ((_b = (_a = process.env.SMARTPAY_API_PREFIX) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("api.smartpay")) ? process.env.SMARTPAY_API_PREFIX : "";
var SMARTPAY_CHECKOUT_URL = process.env.SMARTPAY_CHECKOUT_URL;
var _Smartpay = class {
var SmartpayBase = class {
constructor(key, options = {}) {

@@ -453,3 +468,2 @@ if (!key) {

this._apiPrefix = options.apiPrefix || SMARTPAY_API_PREFIX || API_PREFIX;
this._checkoutURL = options.checkoutURL || SMARTPAY_CHECKOUT_URL || CHECKOUT_URL;
}

@@ -468,3 +482,3 @@ request(endpoint, options = {}) {

"dev-lang": "nodejs",
"sdk-version": "0.6.0"
"sdk-version": "0.7.0"
})

@@ -488,258 +502,769 @@ });

}).then((response) => {
return response.json().catch((error) => {
throw new SmartpayError({
errorCode: "unexpected_error",
statusCode: response.status,
message: `${response.status} ${error.message}`
});
}).then((data) => {
if (response.ok) {
return data;
}
throw new SmartpayError({
errorCode: data.errorCode,
statusCode: response.status,
message: `${response.status} ${data.message}`,
details: data.details
});
});
switch (response.status) {
case 204:
return Promise.resolve("");
default:
return response.json().catch((error) => {
throw new SmartpayError({
errorCode: "unexpected_error",
statusCode: response.status,
message: `${response.status} ${error.message}`
});
}).then((data) => {
if (response.ok) {
return data;
}
throw new SmartpayError({
errorCode: data.errorCode,
statusCode: response.status,
message: `${response.status} ${data.message}`,
details: data.details
});
});
}
});
}
static normalizeCheckoutSessionPayload(payload) {
const normalizedPayload = normalizeCheckoutSessionPayload2(payload);
const errors = validateCheckoutSessionPayload(normalizedPayload);
if (errors.length) {
setPublicKey(publicKey) {
if (!publicKey) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payload invalid",
details: jtdErrorToDetails(errors, "payload")
message: "Public Key is required"
});
}
return normalizedPayload;
if (!isValidPublicApiKey(publicKey)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Public Key is invalid"
});
}
this._publicKey = publicKey;
return {};
}
createCheckoutSession(payload) {
const normalizedPayload = _Smartpay.normalizeCheckoutSessionPayload(payload);
const req = this.request(`/checkout-sessions`, {
method: POST,
idempotencyKey: payload.idempotencyKey,
payload: omit(normalizedPayload, ["idempotencyKey"])
});
return req.then((session) => {
if (session) {
const sessionURL = _Smartpay.getSessionURL(session, {
promotionCode: payload.promotionCode
};
var base_default = SmartpayBase;
// src/Smartpay/checkout-sessions.ts
import qs2 from "query-string";
var ADDRESS_TYPE_HOME = "home";
var ADDRESS_TYPE_GIFT = "gift";
var ADDRESS_TYPE_LOCKER = "locker";
var ADDRESS_TYPE_OFFICE = "office";
var ADDRESS_TYPE_STORE = "store";
var CAPTURE_METHOD_AUTOMATIC = "autommatic";
var CAPTURE_METHOD_MANUAL = "manual";
var checkoutSessionsMixin = (Base) => {
const _SmartpayWithCheckoutSession = class extends Base {
static normalizeCheckoutSessionPayload(payload) {
const normalizedPayload = normalizeCheckoutSessionPayload2(payload);
const errors = validateCheckoutSessionPayload(normalizedPayload);
if (errors.length) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payload invalid",
details: jtdErrorToDetails(errors, "payload")
});
if (sessionURL) {
session.url = sessionURL;
}
return normalizedPayload;
}
createCheckoutSession(payload) {
const normalizedPayload = _SmartpayWithCheckoutSession.normalizeCheckoutSessionPayload(payload);
const req = this.request(`/checkout-sessions`, {
method: POST,
idempotencyKey: payload.idempotencyKey,
payload: omit(normalizedPayload, ["idempotencyKey"])
});
return req.then((session) => {
if (session) {
const sessionURL = _SmartpayWithCheckoutSession.getSessionURL(session, {
promotionCode: payload.promotionCode
});
if (sessionURL) {
session.url = sessionURL;
}
}
return session;
});
}
listCheckoutSessions(params = {}) {
const req = this.request(`/checkout-sessions`, {
method: GET,
params
});
return req;
}
getCheckoutSession(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "CheckoutSession Id is required"
});
}
return session;
});
}
getOrders(params = {}) {
const req = this.request(`/orders`, {
method: GET,
params
});
return req;
}
getOrder(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
if (!isValidCheckoutSessionId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "CheckoutSession Id is invalid"
});
}
const req = this.request(`/checkout-sessions/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
if (!isValidOrderId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
static getSessionUrl(session, options) {
if (!session) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Session is invalid"
});
}
const checkoutURL = session.url;
const params = {
"promotion-code": options == null ? void 0 : options.promotionCode
};
return qs2.stringifyUrl({
url: checkoutURL,
query: params
});
}
const req = this.request(`/orders/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
cancelOrder(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
static getSessionURL(session, options) {
return this.getSessionUrl(session, options);
}
};
let SmartpayWithCheckoutSession = _SmartpayWithCheckoutSession;
SmartpayWithCheckoutSession.ADDRESS_TYPE_HOME = ADDRESS_TYPE_HOME;
SmartpayWithCheckoutSession.ADDRESS_TYPE_GIFT = ADDRESS_TYPE_GIFT;
SmartpayWithCheckoutSession.ADDRESS_TYPE_LOCKER = ADDRESS_TYPE_LOCKER;
SmartpayWithCheckoutSession.ADDRESS_TYPE_OFFICE = ADDRESS_TYPE_OFFICE;
SmartpayWithCheckoutSession.ADDRESS_TYPE_STORE = ADDRESS_TYPE_STORE;
SmartpayWithCheckoutSession.CAPTURE_METHOD_AUTOMATIC = CAPTURE_METHOD_AUTOMATIC;
SmartpayWithCheckoutSession.CAPTURE_METHOD_MANUAL = CAPTURE_METHOD_MANUAL;
return SmartpayWithCheckoutSession;
};
var checkout_sessions_default = checkoutSessionsMixin;
// src/Smartpay/coupons.ts
var COUPON_DISCOUNT_TYPE_AMOUNT = "amount";
var COUPON_DISCOUNT_TYPE_PERCENTAGE = "percentage";
var couponsMixin = (Base) => {
var _a2;
return _a2 = class extends Base {
createCoupon(params = {}) {
const {
name,
discountType,
discountAmount,
currency,
discountPercentage
} = params;
if (!name) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "name is required"
});
}
if (!discountType) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "discountType is required."
});
}
if (![
COUPON_DISCOUNT_TYPE_AMOUNT,
COUPON_DISCOUNT_TYPE_PERCENTAGE
].includes(discountType)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "discountType is invalid."
});
}
if (discountType === COUPON_DISCOUNT_TYPE_AMOUNT && discountAmount == null) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "discount_amount is required if discount_type is amount."
});
}
if (discountType === COUPON_DISCOUNT_TYPE_AMOUNT && !currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "currency is required if discount_amount is provided."
});
}
if (discountType === COUPON_DISCOUNT_TYPE_PERCENTAGE && discountPercentage == null) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "discount_percentage is required if discount_type is percentage."
});
}
const req = this.request(`/coupons`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
if (!isValidOrderId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
getCoupon(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is required"
});
}
if (!isValidCouponId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is invalid"
});
}
const req = this.request(`/coupons/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
const req = this.request(`/orders/${id}/cancellation`, {
method: PUT,
params: omit(params, ["id"]),
idempotencyKey: params.idempotencyKey
});
return req;
}
createPayment(params = {}) {
const { order, amount, currency } = params;
if (!order) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
updateCoupon(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is required"
});
}
if (!isValidCouponId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is invalid"
});
}
const req = this.request(`/coupons/${id}`, {
method: PATCH,
payload: omit(params, ["id"])
});
return req;
}
if (!isValidOrderId(order)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
listCoupons(params = {}) {
const req = this.request(`/coupons`, {
method: GET,
params
});
return req;
}
if (!amount) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Capture Amount is required"
}, _a2.COUPON_DISCOUNT_TYPE_AMOUNT = COUPON_DISCOUNT_TYPE_AMOUNT, _a2.COUPON_DISCOUNT_TYPE_PERCENTAGE = COUPON_DISCOUNT_TYPE_PERCENTAGE, _a2;
};
var coupons_default = couponsMixin;
// src/Smartpay/orders.ts
var ORDER_STATUS_SUCCEEDED = "succeeded";
var ORDER_STATUS_CANCELED = "canceled";
var ORDER_STATUS_REJECTED = "rejected";
var ORDER_STATUS_FAILED = "failed";
var ORDER_STATUS_REQUIRES_AUTHORIZATION = "requires_authorization";
var ordersMixin = (Base) => {
var _a2;
return _a2 = class extends Base {
getOrder(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
});
}
if (!isValidOrderId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
});
}
const req = this.request(`/orders/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
if (!currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Capture Amount Currency is required"
cancelOrder(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
});
}
if (!isValidOrderId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
});
}
const req = this.request(`/orders/${id}/cancellation`, {
method: PUT,
params: omit(params, ["id"]),
idempotencyKey: params.idempotencyKey
});
return req;
}
const req = this.request(`/payments`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
capture(params = {}) {
return this.createPayment(params);
}
getPayment(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is required"
listOrders(params = {}) {
const req = this.request(`/orders`, {
method: GET,
params
});
return req;
}
if (!isValidPaymentId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is invalid"
}, _a2.ORDER_STATUS_SUCCEEDED = ORDER_STATUS_SUCCEEDED, _a2.ORDER_STATUS_CANCELED = ORDER_STATUS_CANCELED, _a2.ORDER_STATUS_REJECTED = ORDER_STATUS_REJECTED, _a2.ORDER_STATUS_FAILED = ORDER_STATUS_FAILED, _a2.ORDER_STATUS_REQUIRES_AUTHORIZATION = ORDER_STATUS_REQUIRES_AUTHORIZATION, _a2;
};
var orders_default = ordersMixin;
// src/Smartpay/payments.ts
var CANCEL_REMAINDER_AUTOMATIC = "autommatic";
var CANCEL_REMAINDER_MANUAL = "manual";
var paymentsMixin = (Base) => {
var _a2;
return _a2 = class extends Base {
createPayment(params = {}) {
const { order, amount, currency } = params;
if (!order) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is required"
});
}
if (!isValidOrderId(order)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Order Id is invalid"
});
}
if (!amount) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Capture Amount is required"
});
}
if (!currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Capture Amount Currency is required"
});
}
const req = this.request(`/payments`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
const req = this.request(`/payments/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
createRefund(params = {}) {
const { payment, amount, currency, reason } = params;
if (!payment) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is required"
capture(params = {}) {
return this.createPayment(params);
}
getPayment(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is required"
});
}
if (!isValidPaymentId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is invalid"
});
}
const req = this.request(`/payments/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
if (!isValidPaymentId(payment)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is invalid"
updatePayment(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is required"
});
}
if (!isValidPaymentId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is invalid"
});
}
const req = this.request(`/payments/${id}`, {
method: PATCH,
payload: omit(params, ["id"])
});
return req;
}
if (!amount) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Amount is required"
listPayments(params = {}) {
const req = this.request(`/payments`, {
method: GET,
params
});
return req;
}
if (!currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Amount Currency is required"
}, _a2.CANCEL_REMAINDER_AUTOMATIC = CANCEL_REMAINDER_AUTOMATIC, _a2.CANCEL_REMAINDER_MANUAL = CANCEL_REMAINDER_MANUAL, _a2;
};
var payments_default = paymentsMixin;
// src/Smartpay/promotion-codes.ts
var COUPON_DISCOUNT_TYPE_AMOUNT2 = "amount";
var COUPON_DISCOUNT_TYPE_PERCENTAGE2 = "percentage";
var promotionCodesMixin = (Base) => {
var _a2;
return _a2 = class extends Base {
createPromotionCode(params = {}) {
const { code, coupon, currency, minimumAmount } = params;
if (!code) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "name is required."
});
}
if (!coupon) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is required."
});
}
if (!isValidCouponId(coupon)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Coupon Id is invalid."
});
}
if (minimumAmount && !currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "CoupCurrency is required if minimum_amount is provided."
});
}
const req = this.request(`/promotion-codes`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
if (!reason) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Reason is required"
getPromotionCode(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Promotion Code Id is required"
});
}
if (!isValidPromotionCodeId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Promotion Code Id is invalid"
});
}
const req = this.request(`/promotion-codes/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
const req = this.request(`/refunds`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
refund(params = {}) {
return this.createRefund(params);
}
getRefund(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is required"
updatePromotionCode(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Promotion Code Id is required"
});
}
if (!isValidPromotionCodeId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Promotion Code Id is invalid"
});
}
const req = this.request(`/promotion-codes/${id}`, {
method: PATCH,
payload: omit(params, ["id"])
});
return req;
}
if (!isValidRefundId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is invalid"
listPromotionCodes(params = {}) {
const req = this.request(`/promotion-codes`, {
method: GET,
params
});
return req;
}
const req = this.request(`/refunds/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
setPublicKey(publicKey) {
if (!publicKey) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Public Key is required"
}, _a2.COUPON_DISCOUNT_TYPE_AMOUNT = COUPON_DISCOUNT_TYPE_AMOUNT2, _a2.COUPON_DISCOUNT_TYPE_PERCENTAGE = COUPON_DISCOUNT_TYPE_PERCENTAGE2, _a2;
};
var promotion_codes_default = promotionCodesMixin;
// src/Smartpay/refunds.ts
var REFUND_REQUEST_BY_CUSTOMER = "requested_by_customer";
var REFUND_FRAUDULENT = "fraudulent";
var refundsMixin = (Base) => {
var _a2;
return _a2 = class extends Base {
createRefund(params = {}) {
const { payment, amount, currency, reason } = params;
if (!payment) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is required"
});
}
if (!isValidPaymentId(payment)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Payment Id is invalid"
});
}
if (!amount) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Amount is required"
});
}
if (!currency) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Amount Currency is required"
});
}
if (!reason) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Reason is required"
});
}
if (![REFUND_REQUEST_BY_CUSTOMER, REFUND_FRAUDULENT].includes(reason)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Reason is invalid"
});
}
const req = this.request(`/refunds`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
if (!isValidPublicApiKey(publicKey)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Public Key is invalid"
refund(params = {}) {
return this.createRefund(params);
}
getRefund(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is required"
});
}
if (!isValidRefundId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is invalid"
});
}
const req = this.request(`/refunds/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
this._publicKey = publicKey;
return {};
}
static getSessionURL(session, options) {
if (!session) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Session is invalid"
updateRefund(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is required"
});
}
if (!isValidRefundId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Refund Id is invalid"
});
}
const req = this.request(`/refunds/${id}`, {
method: PATCH,
payload: omit(params, ["id"])
});
return req;
}
const checkoutURL = session.url;
const params = {
"promotion-code": options == null ? void 0 : options.promotionCode
};
return qs.stringifyUrl({
url: checkoutURL,
query: params
});
}
listRefunds(params = {}) {
const req = this.request(`/refunds`, {
method: GET,
params
});
return req;
}
}, _a2.REFUND_REQUEST_BY_CUSTOMER = REFUND_REQUEST_BY_CUSTOMER, _a2.REFUND_FRAUDULENT = REFUND_FRAUDULENT, _a2;
};
var Smartpay = _Smartpay;
Smartpay.REJECT_REQUEST_BY_CUSTOMER = "requested_by_customer";
Smartpay.REJECT_FRAUDULENT = "fraudulent";
var smartpay_default = Smartpay;
var refunds_default = refundsMixin;
// src/Smartpay/webhooks.ts
import { createHmac } from "crypto";
import basex from "base-x";
var BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var base62 = basex(BASE62);
var webhooksMixin = (Base) => {
return class extends Base {
createWebhookEndpoint(params = {}) {
const { url } = params;
if (!url) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "URL is required"
});
}
const req = this.request(`/webhook-endpoints`, {
method: POST,
idempotencyKey: params.idempotencyKey,
payload: omit(params, ["idempotencyKey"])
});
return req;
}
getWebhookEndpoint(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is required"
});
}
if (!isValidWebhookEndpointId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is invalid"
});
}
const req = this.request(`/webhook-endpoints/${id}`, {
method: GET,
params: omit(params, ["id"])
});
return req;
}
updateWebhookEndpoint(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is required"
});
}
if (!isValidWebhookEndpointId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is invalid"
});
}
const req = this.request(`/webhook-endpoints/${id}`, {
method: PATCH,
payload: omit(params, ["id"])
});
return req;
}
deleteWebhookEndpoint(params = {}) {
const { id } = params;
if (!id) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is required"
});
}
if (!isValidWebhookEndpointId(id)) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "Webhook Endpoint Id is invalid"
});
}
const req = this.request(`/webhook-endpoints/${id}`, {
method: DELETE
});
return req;
}
listWebhookEndpoints(params = {}) {
const req = this.request(`/webhook-endpoints`, {
method: GET,
params
});
return req;
}
static calculateWebhookSignature(params) {
const { data, secret } = params;
if (!data) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "data is required"
});
}
if (!secret) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "secret is required"
});
}
const signer = createHmac("sha256", Buffer.from(base62.decode(secret)));
const result = signer.update(Buffer.from(data, "utf8")).digest("hex");
return result;
}
static verifyWebhookSignature(params) {
const { data, secret, signature } = params;
if (!data) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "data is required"
});
}
if (!secret) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "secret is required"
});
}
if (!signature) {
throw new SmartpayError({
errorCode: "request.invalid",
message: "signature is required"
});
}
const calculatedSignature = this.calculateWebhookSignature({
data,
secret
});
return signature === calculatedSignature;
}
static expressWebhookMiddleware(secret) {
return (req, res, buf) => {
if (req.headers["smartpay-signature"]) {
const subscriptionId = req.headers["smartpay-subscription-id"];
const signingSecret = typeof secret === "string" ? secret : secret(subscriptionId);
const signer = createHmac("sha256", Buffer.from(base62.decode(signingSecret)));
const signatureTimestamp = req.headers["smartpay-signature-timestamp"];
const result = signer.update(Buffer.from(`${signatureTimestamp}.`, "utf8")).update(buf).digest("hex");
req.headers["calculated-signature"] = result;
}
};
}
};
};
var webhooks_default = webhooksMixin;
// src/Smartpay/index.ts
var mixins = [
checkout_sessions_default,
orders_default,
payments_default,
refunds_default,
webhooks_default,
coupons_default,
promotion_codes_default
];
var Smartpay = mixins.reduce((previousClass, mixin) => mixin(previousClass), base_default);
var Smartpay_default = Smartpay;
// src/index.ts
var src_default = smartpay_default;
var src_default = Smartpay_default;
export {

@@ -746,0 +1271,0 @@ src_default as default,

@@ -111,7 +111,8 @@ import type { CustomerInfo, CustomerInfoLoose, SimpleLineItem, SimpleChekoutSessionPayload, ShippingInfo, Address } from './types';

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};

@@ -160,9 +161,10 @@ declare const _default: {

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};
};
export default _default;

@@ -1,2 +0,4 @@

import { KeyString, SmartPayOptions, CheckoutSession, SimpleChekoutSessionPayload, Payment, Refund, Order, GetOrdersParams, GetOrderParams, CancelOrderParams, CreatePaymentParams, GetPaymentParams, CreateRefundParams, GetRefundParams, OrdersCollection } from './types';
/// <reference types="node" />
import { Request, Response } from 'express';
import { KeyString, SmartPayOptions, CheckoutSession, SimpleChekoutSessionPayload, Payment, Refund, Order, GetOrdersParams, GetOrderParams, CancelOrderParams, CreatePaymentParams, GetPaymentParams, CreateRefundParams, GetRefundParams, OrdersCollection, CalculateWebhookSignatureParams, VerifyWebhookSignatureParams } from './types';
interface Params {

@@ -45,4 +47,8 @@ [key: string]: string | number;

setPublicKey(publicKey: KeyString): {};
static getSessionUrl(session: CheckoutSession, options?: GetSessionURLOptions): string;
static getSessionURL(session: CheckoutSession, options?: GetSessionURLOptions): string;
static calculateWebhookSignature(params: CalculateWebhookSignatureParams): string;
static verifyWebhookSignature(params: VerifyWebhookSignatureParams): boolean;
static expressWebhookMiddleware(secret: string | Function): (req: Request, res: Response, buf: Buffer) => void;
}
export default Smartpay;

@@ -135,7 +135,8 @@ export interface LooseObject {

customerInfo?: CustomerInfo;
locale?: string;
successUrl?: string;
cancelUrl?: string;
description?: string;
metadata?: MetaData;
reference?: string;
successUrl?: string;
cancelUrl?: string;
promotionCode?: string;

@@ -236,2 +237,50 @@ idempotencyKey?: string;

};
export declare type WebhookEndpoint = {
id: string;
object: string;
active: boolean;
createdAt: number;
description?: string;
eventSubscriptions: string[];
metadata?: MetaData;
test: boolean;
url: string;
updatedAt: number;
};
export declare type Coupon = {
id: string;
object: string;
active: boolean;
name: string;
createdAt: number;
currency?: string;
description?: string;
discountAmount?: number;
discountPercentage?: number;
discountType: string;
expiresAt?: number;
maxRedemptionCount?: number;
redemptionCount: number;
sponsored: boolean;
metadata?: MetaData;
test: boolean;
updatedAt: number;
};
export declare type PromotionCode = {
id: string;
object: string;
active: boolean;
code: string;
createdAt: number;
currency?: string;
expiresAt?: number;
firstTimeTransaction: boolean;
onePerCustomer: boolean;
maxRedemptionCount?: number;
redemptionCount: number;
minimumAmount?: number;
metadata?: MetaData;
test: boolean;
updatedAt: number;
};
export declare type JTDError = {

@@ -241,3 +290,3 @@ instancePath: string[];

};
export declare type GetOrdersParams = {
export declare type ListParams = {
expand?: string;

@@ -247,14 +296,6 @@ pageToken?: string;

};
export declare type GetOrderParams = {
export declare type GetObjectParams = {
id?: string;
expand?: string;
};
export declare type GetPaymentParams = {
id?: string;
expand?: string;
};
export declare type GetRefundParams = {
id?: string;
expand?: string;
};
export declare type CancelOrderParams = {

@@ -274,2 +315,8 @@ id?: string;

};
export declare type UpdatePaymentParams = {
id?: string;
reference?: string;
description?: string;
metadata?: MetaData;
};
export declare type CreateRefundParams = {

@@ -285,3 +332,61 @@ payment?: string;

};
export declare type OrdersCollection = {
export declare type UpdateRefundParams = {
id?: string;
reference?: string;
description?: string;
metadata?: MetaData;
};
export declare type CreateWebhookEndpointParams = {
url?: string;
description?: string;
eventSubscriptions?: string[];
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdateWebhookEndpointParams = CreateWebhookEndpointParams & {
id?: string;
active?: boolean;
};
export declare type CreateCouponParams = {
name?: string;
currency?: string;
description?: string;
discountAmount?: number;
discountPercentage?: number;
discountType?: string;
expiresAt?: number;
maxRedemptionCount?: number;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdateCouponParams = {
id?: string;
active?: boolean;
name?: string;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type CreatePromotionCodeParams = {
active?: boolean;
code?: string;
coupon?: string;
currency?: string;
expiresAt?: number;
firstTimeTransaction?: boolean;
onePerCustomer?: boolean;
maxRedemptionCount?: number;
minimumAmount?: number;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type UpdatePromotionCodeParams = {
id?: string;
active?: boolean;
metadata?: MetaData;
idempotencyKey?: string;
};
export declare type DeleteObjectParams = {
id?: string;
};
export declare type Collection<T> = {
object: string;

@@ -292,6 +397,13 @@ pageToken: string;

results: number;
data: Array<Order>;
data: Array<T>;
};
export declare type CalculateWebhookSignatureParams = {
data: string;
secret: string;
};
export declare type VerifyWebhookSignatureParams = CalculateWebhookSignatureParams & {
signature: string;
};
export declare type ErrorDetail = any;
export declare type ErrorDetails = ErrorDetail[];
export {};

@@ -19,2 +19,5 @@ import type { KeyString, SimpleChekoutSessionPayload, ErrorDetails, LooseObject } from './types';

export declare const isValidRefundId: (input: string) => boolean;
export declare const isValidWebhookEndpointId: (input: string) => boolean;
export declare const isValidCouponId: (input: string) => boolean;
export declare const isValidPromotionCodeId: (input: string) => boolean;
export declare const validateCheckoutSessionPayload: (payload: SimpleChekoutSessionPayload) => ErrorDetails;

@@ -66,7 +69,8 @@ /**

};
locale: string | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
reference: string | undefined;
description: string | undefined;
metadata: import("./types").MetaData | undefined;
successUrl: string | undefined;
cancelUrl: string | undefined;
};

@@ -73,0 +77,0 @@ export declare const omit: (obj: LooseObject, omitKeys: string[]) => {

@@ -7,3 +7,3 @@ {

},
"version": "0.6.0",
"version": "0.7.0",
"description": "Smartpay SDK NodeJS",

@@ -51,2 +51,4 @@ "main": "./build/cjs/index.cjs",

"devDependencies": {
"@types/express": "^4.17.13",
"@types/randomstring": "^1.1.8",
"@typescript-eslint/eslint-plugin": "^4.4.1",

@@ -78,2 +80,3 @@ "@typescript-eslint/parser": "^4.28.2",

"dependencies": {
"base-x": "^4.0.0",
"fetch-retry": "^5.0.2",

@@ -80,0 +83,0 @@ "isomorphic-unfetch": "^3.1.0",

@@ -66,10 +66,4 @@ # Smartpay Nodejs SDK

We supports two formats of the checkout session payload. The first one is strict format. You will have the
full control to the session payload if you choose to use strict format. Please checkout the API [document][strict-session] for more information about the strict format.
The shape of checkout session payload is described in the [docuement](https://en.docs.smartpay.co/reference/create-a-checkout-session).
The second supported format is loose format. This format is a less complexity version of the strict format.
Our SDK will transform the payload to strict format before sending to our API endpoint.
[strict-session]: https://documenter.getpostman.com/view/16470887/U16dSU8B#8a3538b1-530c-448c-8bae-4a41cdf0b8fd
### To retreive the session URL

@@ -82,1 +76,5 @@

We also prepare a more [real-world example](https://github.com/smartpay-co/integration-examples/blob/main/server/node/server.js) for you to refer to.
## Reference
Please check the [reference](docs/Reference.md) document.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc