@fype/sdk
v1.0.0
Published
Fype Payments Client SDK for Node.js and TypeScript
Maintainers
Readme
Fype Node.js & TypeScript Client SDK
The official, zero-dependency Node.js and TypeScript client library for the Fype Payments Orchestration Layer. Fully type-safe, async-friendly, and lightweight, it simplifies payment creations, refunds, and timing-safe webhook signature verifications under a unified API interface.
Features
- TypeScript First: Hand-crafted type definitions for all requests and responses.
- Zero Runtime Dependencies: Ultra-light footprint using native Node.js
fetch(Node 18+) and standardcryptoAPIs. - Dual-Package Output: Out-of-the-box support for ES Modules (
import) and CommonJS (require). - Timing-Safe Webhook Checks: Prevents cryptographic side-channel timing analysis attacks using standard
crypto.timingSafeEqualover buffers. - Pristine Consistency: Unified API structure identical to the Fype Python SDK.
Installation
Install the package directly inside your local Node.js application:
npm install packages/nodejs-sdk(Or via npm registry once distributed):
npm install fypeQuick Start
1. Initialize Client
Expose your Fype developer API key (use test key for sandbox or live key for production):
import { Fype } from "fype";
// Initialize the client
const fype = new Fype({
apiKey: "fype_test_your_secret_api_key_here",
});2. Create Hosted Checkout Session
Initiate a payment order. Fype will automatically contact gateway adapters under the hood and return a public buyer-facing checkout URL:
const payment = await fype.payments.create({
amount: 25000, // Amount in paise (₹250.00 INR)
currency: "INR",
customer_email: "[email protected]",
success_url: "https://yourwebsite.com/payment/success",
cancel_url: "https://yourwebsite.com/payment/cancel",
reference_id: "order_ref_1092", // Optional merchant order ID
provider: "cashfree" // Optional: Explicitly choose gateway (razorpay/cashfree)
});
console.log(`Transaction ID: ${payment.id}`);
console.log(`Checkout URL: ${payment.checkout_url}`);3. Dynamic Redirect Placeholders
Like Stripe, Fype natively supports dynamic placeholders inside success_url and cancel_url redirect strings. This allows you to build frictionless, stateless checkout loops (e.g. for login-free purchases).
Fype will automatically replace these placeholders before redirecting the buyer back to your website:
{CHECKOUT_SESSION_ID}: Replaced with the actual Fype Checkout Session UUID.{PAYMENT_ID}: Replaced with the actual Fype Payment UUID (useful for direct API validation).
Example:
const payment = await fype.payments.create({
amount: 25000,
currency: "INR",
customer_email: "[email protected]",
success_url: "https://yourwebsite.com/payment/success?fype_session_id={PAYMENT_ID}",
cancel_url: "https://yourwebsite.com/payment/cancel"
});4. Retrieve Payment Details
Audit checkout session status at any time:
const payment = await fype.payments.retrieve("pay_test_abc123");
console.log(`Current Status: ${payment.status}`); // 'created', 'succeeded', 'failed', etc.4. List Payments with Keyset Cursor Pagination
Audit transactions with high-performance keyset paging limits:
const result = await fype.payments.list({
limit: 10,
cursor: "eyJ2IjoxLCJ0IjoiMjAyNi0wNS0yN1QxMjo1OTo1OC4xMDBaIiwiaSI6InBheV8xMjMifQ"
});
console.log(`Total items retrieved: ${result.payments.length}`);
console.log(`Has more items: ${result.has_more}`);
console.log(`Next page cursor: ${result.next_cursor}`);5. Issue a Refund
Perform partial or full refunds for successful payments:
// Full Refund (omit amount parameter)
const refund = await fype.refunds.create({
payment_id: "pay_test_abc123"
});
// Partial Refund (specify amount in paise)
const partialRefund = await fype.refunds.create({
payment_id: "pay_test_abc123",
amount: 5000
});Webhook Signature Verification
Incoming HTTP webhook events are cryptographically signed by Fype. Always verify signatures against your webhook signing secret (whsec_...) to prevent spoofing. The SDK handles constant-time HMAC comparison internally to guard against side-channel timing analysis attacks:
import { FypeSignatureVerificationError } from "fype";
const rawBody = request.rawBody; // Get raw request body (string or Buffer)
const signature = request.headers["x-fype-signature"] as string;
const secret = "whsec_your_webhook_signing_secret";
try {
fype.webhooks.verifySignature(rawBody, signature, secret);
console.log("Webhook signature is valid and authentic!");
// Proceed to handle events (e.g. payment.succeeded)
} catch (error) {
if (error instanceof FypeSignatureVerificationError) {
console.error(`Invalid webhook signature: ${error.message}`);
}
}Error Handling
The SDK exposes explicit, catchable exception classes to let you handle failures gracefully:
import {
FypeAuthenticationError,
FypeInvalidRequestError,
FypeApiConnectionError,
FypeError
} from "fype";
try {
const payment = await fype.payments.create({ ... });
} catch (error) {
if (error instanceof FypeAuthenticationError) {
// Handle bad API keys
console.error("Invalid Fype API key.");
} else if (error instanceof FypeInvalidRequestError) {
// Handle validation errors (e.g. invalid currency, negative amount)
console.error(`Request failed validation: ${error.message}`);
} else if (error instanceof FypeApiConnectionError) {
// Handle network timeouts or unreachable hosts
console.error(`Connection failed or timed out: ${error.message}`);
} else if (error instanceof FypeError) {
// Handle server-side errors
console.error(`Fype gateway server error: ${error.message}`);
}
}Developer Operations (DevOps)
Build SDK
Generate output bundles in CommonJS (.js), ESM (.mjs), and TypeScript definitions:
npm run buildRun Native Test Suite
Trigger fast local unit test assertions on Node's native test framework:
npm test