npm package: @probuy/backend-sdk
Description: ProBuy Backend SDK - Server-side payment integration for Node.js
Author: ProBuy Team
Latest version: 0.0.4

# @probuy/backend-sdk

ProBuy Backend SDK للـ Node.js - Server-side only payment integration.

## Installation

```bash
npm install @probuy/backend-sdk
```

## Quick Start

```javascript
import { ProBuyBackendSDK } from "@probuy/backend-sdk";

// Initialize SDK
const probuy = new ProBuyBackendSDK({
  apiToken: process.env.PROBUY_API_TOKEN,
  environment: "sandbox", // 'sandbox' or 'prod'
  debug: true,
});

// Create checkout session
const session = await probuy.createCheckoutSession({
  order_reference_id: "order-123",
  order_number: "ORD-123",
  currency: "SAR",
  total_amount: 1000,
  item: {
    name: "Product Name",
    description: "Product Description",
    type: "Physical",
    reference_id: "prod-1",
    sku: "SKU-123",
    quantity: 1,
    unit_price: 1000,
    total_amount: 1000,
    tax_amount: 0,
    discount_amount: 0,
  },
  consumer: {
    email: "customer@example.com",
    first_name: "John",
    last_name: "Doe",
    phone_number: "+966501234567",
  },
  country_code: "SA",
  merchant_url: {
    success: "https://yoursite.com/success",
    failure: "https://yoursite.com/failure",
    cancel: "https://yoursite.com/cancel",
  },
  billing_address: {
    first_name: "John",
    last_name: "Doe",
    line1: "123 Main St",
    city: "Riyadh",
    region: "Riyadh",
    country_code: "SA",
    phone_number: "+966501234567",
  },
  shipping_address: {
    first_name: "John",
    last_name: "Doe",
    line1: "123 Main St",
    city: "Riyadh",
    region: "Riyadh",
    country_code: "SA",
    phone_number: "+966501234567",
  },
});

console.log("Checkout created:", session.checkout_id);
console.log(
  "Redirect customer to:",
  probuy.getCheckoutUrl(session.checkout_id)
);
```

## Features

- ✅ **Server-side only** - No browser/frontend code
- ✅ **TypeScript support** - Full type definitions included
- ✅ **Simple API** - Easy to integrate
- ✅ **Environment support** - sandbox, production
- ✅ **Error handling** - Comprehensive error types
- ✅ **Secure** - API token never exposed to client

## API Reference

### Constructor

```typescript
const probuy = new ProBuyBackendSDK(config: ProBuyConfig)
```

**ProBuyConfig:**

- `apiToken` (string, required) - Your ProBuy API token
- `environment` ('sandbox' | 'prod', optional) - Default: 'sandbox'
- `timeout` (number, optional) - Request timeout in ms
- `retryCount` (number, optional) - Number of retries
- `debug` (boolean, optional) - Enable debug logging

#### Available Environments

| Environment | API Base URL | Company Portal URL |
|-------------|--------------|-------------------|
| **Sandbox** | `https://sandboxapi.probuy.dev` | `https://sandboxcompany.probuy.dev` |
| **Production** | `https://api.probuy.me` | `https://company.probuy.me` |

**Note:** Only `sandbox` and `prod` environments are available for public use.

### Methods

#### createCheckoutSession(orderData)

Creates a new checkout session.

```typescript
const session = await probuy.createCheckoutSession(orderData);
```

**Returns:** `CheckoutSessionResponse`

```typescript
{
  checkout_id: string;
  order_reference_id: string;
  checkout_url: string;
  status: string;
  expires_at: string;
  created_at: string;
}
```

#### getCheckoutDetails(checkoutId)

Get details of an existing checkout session.

```typescript
const details = await probuy.getCheckoutDetails("chk_123");
```

**Returns:** `CheckoutDetailedResponse`

#### getCheckoutUrl(checkoutId)

Get the full checkout URL for redirecting customers.

```typescript
const url = probuy.getCheckoutUrl("chk_123");
// Returns: https://sandboxcompany.probuy.dev/checkout/chk_123 (sandbox)
// Returns: https://company.probuy.me/checkout/chk_123 (production)
```

#### createCheckoutWithRedirectUrl(orderData)

Convenience method that creates session and returns redirect URL in one call.

```typescript
const result = await probuy.createCheckoutWithRedirectUrl(orderData);
console.log(result.redirect_url);
```

**Returns:** `CheckoutSessionResponse & { redirect_url: string }`

## Usage Examples

### Express.js Integration

```javascript
import express from "express";
import { ProBuyBackendSDK } from "@probuy/backend-sdk";

const app = express();
app.use(express.json());

// Initialize SDK
const probuy = new ProBuyBackendSDK({
  apiToken: process.env.PROBUY_API_TOKEN,
  environment: process.env.NODE_ENV === "production" ? "prod" : "sandbox",
});

// Create checkout endpoint
app.post("/api/checkout/create", async (req, res) => {
  try {
    const session = await probuy.createCheckoutWithRedirectUrl(req.body);

    res.json({
      success: true,
      checkout_id: session.checkout_id,
      redirect_url: session.redirect_url,
    });
  } catch (error) {
    console.error("Checkout error:", error);
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

// Get checkout status endpoint
app.get("/api/checkout/:id", async (req, res) => {
  try {
    const details = await probuy.getCheckoutDetails(req.params.id);
    res.json({ success: true, data: details });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});
```

### NestJS Integration

```typescript
import { Injectable } from "@nestjs/common";
import { ProBuyBackendSDK } from "@probuy/backend-sdk";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class PaymentService {
  private probuy: ProBuyBackendSDK;

  constructor(private config: ConfigService) {
    this.probuy = new ProBuyBackendSDK({
      apiToken: this.config.get("PROBUY_API_TOKEN"),
      environment: this.config.get("PROBUY_ENVIRONMENT"),
    });
  }

  async createCheckout(orderData: any) {
    return await this.probuy.createCheckoutWithRedirectUrl(orderData);
  }

  async getCheckoutStatus(checkoutId: string) {
    return await this.probuy.getCheckoutDetails(checkoutId);
  }
}
```

### Fastify Integration

```javascript
import Fastify from "fastify";
import { ProBuyBackendSDK } from "@probuy/backend-sdk";

const fastify = Fastify({ logger: true });

const probuy = new ProBuyBackendSDK({
  apiToken: process.env.PROBUY_API_TOKEN,
  environment: "sandbox",
});

fastify.post("/checkout/create", async (request, reply) => {
  try {
    const session = await probuy.createCheckoutWithRedirectUrl(request.body);
    return { success: true, data: session };
  } catch (error) {
    reply.code(500);
    return { success: false, error: error.message };
  }
});

fastify.listen({ port: 3000 });
```

## Error Handling

The SDK provides specific error types:

```typescript
import {
  ProBuyError,
  ProBuyValidationError,
  ProBuyAuthenticationError,
  ProBuyNetworkError,
  ProBuyApiError,
} from "@probuy/backend-sdk";

try {
  const session = await probuy.createCheckoutSession(orderData);
} catch (error) {
  if (error instanceof ProBuyValidationError) {
    console.error("Validation error:", error.message, error.details);
  } else if (error instanceof ProBuyAuthenticationError) {
    console.error("Authentication error:", error.message);
  } else if (error instanceof ProBuyNetworkError) {
    console.error("Network error:", error.message);
  } else if (error instanceof ProBuyApiError) {
    console.error("API error:", error.statusCode, error.message);
  } else {
    console.error("Unknown error:", error);
  }
}
```

## TypeScript Support

Full TypeScript definitions included:

```typescript
import {
  ProBuyBackendSDK,
  ProBuyConfig,
  CheckoutOrderData,
  CheckoutSessionResponse,
  CheckoutDetailedResponse,
} from "@probuy/backend-sdk";

const config: ProBuyConfig = {
  apiToken: process.env.PROBUY_API_TOKEN!,
  environment: "sandbox",
  debug: true,
};

const probuy = new ProBuyBackendSDK(config);

const orderData: CheckoutOrderData = {
  // Full type safety
  order_reference_id: "order-123",
  // ...
};

const session: CheckoutSessionResponse = await probuy.createCheckoutSession(
  orderData
);
```

## Environment Variables

Recommended `.env` setup:

```env
# ProBuy Configuration
PROBUY_API_TOKEN=your_api_token_here
PROBUY_ENVIRONMENT=sandbox  # 'sandbox' or 'prod'
PROBUY_DEBUG=true

# Server Configuration
NODE_ENV=development
PORT=3000
```

## Security Best Practices

### ✅ Do's

- Store API token in environment variables
- Use server-side only (never expose token to client)
- Validate order data before sending to ProBuy
- Handle errors appropriately
- Use HTTPS in production
- Rotate API tokens regularly

### ❌ Don'ts

- Never commit API tokens to git
- Never expose tokens in client-side code
- Never log full API tokens
- Don't disable SSL verification
- Don't use development keys in production

## Testing

### Mock SDK for Testing

```javascript
// test/mocks/probuy.mock.js
export class MockProBuySDK {
  async createCheckoutSession(orderData) {
    return {
      checkout_id: "test_checkout_123",
      order_reference_id: orderData.order_reference_id,
      checkout_url: "https://sandboxcompany.probuy.dev/checkout/test_123",
      status: "pending",
      expires_at: new Date(Date.now() + 3600000).toISOString(),
      created_at: new Date().toISOString(),
    };
  }

  async getCheckoutDetails(checkoutId) {
    return {
      checkout_id: checkoutId,
      status: 200,
      // ... other fields
    };
  }

  getCheckoutUrl(checkoutId) {
    return `https://sandboxcompany.probuy.dev/checkout/${checkoutId}`;
  }
}
```

## Troubleshooting

### Authentication Error

**Problem:** `ProBuyAuthenticationError: Invalid API token`

**Solution:**

- Check that your API token is correct
- Verify token hasn't expired
- Ensure you're using the right environment (sandbox/prod)

### Validation Error

**Problem:** `ProBuyValidationError: Missing required fields`

**Solution:**

- Check all required fields are present in order data
- Verify data types match the schema
- Ensure amounts are positive numbers

### Network Error

**Problem:** `ProBuyNetworkError: Request timeout`

**Solution:**

- Check your internet connection
- Increase timeout in config
- Verify ProBuy API is accessible

## Support

- 📖 [API Documentation](https://docs.probuy.me)
- 💬 [Support](mailto:info@probuy.me)
- 🐛 [Report Issues](https://github.com/probuy/backend-sdk/issues)

## License

MIT

---

Made with ❤️ by ProBuy Team