npm package: @stackproviders/payment-sdk
Description: TypeScript SDK for the Payment Platform API
Author: stackproviders.com
Latest version: 1.0.4

# @stackproviders/payment-sdk

> Official TypeScript SDK for the **StackProviders Payment Platform API** — auto-generated, type-safe, and ready for production.

[![npm version](https://img.shields.io/npm/v/@stackproviders/payment-sdk.svg?style=flat-square)](https://www.npmjs.com/package/@stackproviders/payment-sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-square)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](https://opensource.org/licenses/MIT)

The `@stackproviders/payment-sdk` is a lightweight, heavily typed API client for interacting with the StackProviders backend. It seamlessly handles authentication, response parsing, and error typing, making it a perfect fit for both human developers and AI assistants.

---

## 🚀 Installation

Install the package via your preferred package manager:

```bash
# npm
npm install @stackproviders/payment-sdk

# pnpm (Recommended)
pnpm add @stackproviders/payment-sdk

# yarn
yarn add @stackproviders/payment-sdk
```

---

## 🛠 Integration & Setup

The SDK uses an internal interceptor for API keys. This means you only configure the client once globally.

### 1. Configure the Client

```typescript
import { client } from "@stackproviders/payment-sdk";

// Set base URL
client.setConfig({
  baseUrl: process.env.PAYMENT_API_URL || "https://payment.stackprovider.com/api/v1", // Defaults to your env or prod URL
});

// Attach API Key via Request Interceptor
client.interceptors.request.use((request) => {
  const apiKey = process.env.PAYMENT_API_KEY;
  if (!apiKey) {
    console.warn("PAYMENT_API_KEY is not set.");
  }
  // Choose Bearer or x-api-key depending on your backend expectation
  request.headers.set("Authorization", `Bearer ${apiKey}`);
  // Alternatively: request.headers.set("x-api-key", apiKey);
  
  return request;
});
```

---

## 💻 Full Usage Examples

### Create a Checkout Session

Initiate a checkout session to receive a hosted checkout URL.

```typescript
import { client } from "@stackproviders/payment-sdk";
import type { CreateCheckoutSessionRequest } from "@stackproviders/payment-sdk";

async function initiatePayment() {
  const payload: CreateCheckoutSessionRequest = {
    amount: 1500, // Amount in your smallest unit / or integer
    currency: "BDT",
    customerEmail: "user@example.com",
    successUrl: "https://your-site.com/success?sessionId={CHECKOUT_SESSION_ID}",
    cancelUrl: "https://your-site.com/cancel",
    metadata: {
      orderId: "ORD-9999",
      userId: "usr_abc123"
    }
  };

  const { data, error } = await client.post({
    url: "/api/v1/checkout/sessions",
    body: payload,
  });

  if (error) {
    console.error("Failed to create session:", error.error.message);
    return;
  }

  if (data?.success) {
    console.log("Redirect URL:", data.data.checkoutUrl);
    console.log("Session ID:", data.data.id);
  }
}
```

### Retrieve a Checkout Session

Verify payment status after the user returns from the checkout flow.

```typescript
import { client } from "@stackproviders/payment-sdk";

async function verifyPayment(sessionId: string) {
  const { data, error } = await client.get({
    url: "/api/v1/checkout/sessions/{id}",
    path: { id: sessionId },
  });

  if (error) {
    console.error("Error retrieving session:", error.error.code);
    return;
  }

  if (data?.success) {
    const session = data.data;
    if (session.status === "SUCCESS") {
      console.log("Payment completed successfully for amount:", session.amount);
      // Fulfill the order
    } else {
      console.log("Payment status is:", session.status);
    }
  }
}
```

---

## 🤖 AI & Developer Friendly 

This SDK is specifically designed to be easily digestible for both humans and AI coders:

1. **JSDoc & TypeScript Ecosystem**: All types like `CheckoutSession`, `CreateCheckoutSessionRequest`, and `ClientOptions` are correctly exported.
2. **Standardized Responses**: Every API call returns a signature `{ data, error }`. You never need `try/catch` for network failures, unless configured directly via underlying fetch.
3. **Structured Errors**: 

```typescript
if (error) {
  // error.error.code => e.g., "VALIDATION_ERROR"
  // error.error.message => e.g., "Amount must be positive."
}
```

### Exported Types

If you are generating types or writing wrappers, always import standard types:

```typescript
import type { CheckoutSession, CreateCheckoutSessionRequest, ClientOptions } from "@stackproviders/payment-sdk";
```

---

## 📦 Building the Package

If you are cloning this monorepo to build the SDK from source:

```bash
# Generate the OpenAPI types directly from the backend
pnpm prebuild

# Build the TS SDK (ESM and CJS sizes via tsup)
pnpm build
```

The compiled assets will be placed in the `/dist` directory.

---

## 📚 API Reference Links

- **Interactive Docs**: [https://payment.stackprovider.com/api/v1/docs](https://payment.stackprovider.com/api/v1/docs)
- **OpenAPI JSON**: [https://payment.stackprovider.com/api/v1/openapi.json](https://payment.stackprovider.com/api/v1/openapi.json)

## License

[MIT](LICENSE) © StackProviders