> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sahelpay.ml/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK

> SDK JavaScript/TypeScript pour SahelPay

# JavaScript SDK

Le SDK JavaScript officiel pour intégrer SahelPay dans vos applications Node.js, TypeScript ou Deno.

## Installation

```bash theme={null}
npm install @sahelpay/sdk
# ou
yarn add @sahelpay/sdk
```

<Note>
  En attendant la publication sur npm, clonez le repo GitHub :

  ```bash theme={null}
  git clone https://github.com/dione24/sahelpay-sdks.git
  ```
</Note>

## Configuration

```typescript theme={null}
import SahelPay from '@sahelpay/sdk';

const sahelpay = new SahelPay({
  secretKey: process.env.SAHELPAY_SECRET_KEY!,
  environment: 'production' // ou 'sandbox'
});
```

## Créer un paiement

```typescript theme={null}
const payment = await sahelpay.payments.create({
  amount: 5000,
  currency: 'XOF',
  payment_method: 'ORANGE_MONEY', // ORANGE_MONEY, WAVE, MOOV, CARD
  customer_phone: '+22370123456',
  return_url: 'https://votre-site.com/checkout/return',
  description: 'Commande #123',
});

// Rediriger le client vers Orange Money
window.location.href = payment.redirect_url;
```

## Méthodes de paiement disponibles

| Méthode        | Description                  | Pays              |
| -------------- | ---------------------------- | ----------------- |
| `ORANGE_MONEY` | Orange Money                 | Mali, Sénégal, CI |
| `WAVE`         | Wave                         | Mali, Sénégal, CI |
| `MOOV`         | Moov Money                   | Mali, Bénin, Togo |
| `CARD`         | Carte bancaire (VISA/MC/GIM) | Tous              |
| `VISA`         | Carte VISA                   | Tous              |
| `MASTERCARD`   | Carte Mastercard             | Tous              |
| `GIM_UEMOA`    | Carte GIM-UEMOA              | UEMOA             |

<Note>
  SahelPay utilise un **Smart Routing** automatique. Vous spécifiez la méthode de paiement (ex: `ORANGE_MONEY`) et SahelPay choisit le meilleur gateway en interne selon le coût et la disponibilité.
</Note>

## Vérifier le statut

```typescript theme={null}
const status = await sahelpay.getPaymentStatus('txn_abc123');

console.log(status.status); // 'PENDING' | 'SUCCESS' | 'FAILED' | 'EXPIRED'
console.log(status.amount);
console.log(status.providerRef);
```

## Vérifier un webhook

```typescript theme={null}
// Dans votre handler webhook
export async function POST(request: Request) {
  const rawBody = await request.text();
  const signature = request.headers.get('x-sahelpay-signature');

  const result = sahelpay.verifyWebhook(rawBody, signature);

  if (!result.valid) {
    return Response.json({ error: result.error }, { status: 401 });
  }

  const { event, data } = result.payload!;

  if (event === 'payment.success') {
    // Mettre à jour la commande
  }

  return Response.json({ received: true });
}
```

## Types TypeScript

```typescript theme={null}
import type {
  PaymentResult,
  PaymentStatus,
  WebhookPayload,
  WebhookVerificationResult,
} from '@sahelpay/sdk/merchant';
```

## Gestion des erreurs

```typescript theme={null}
import { SahelPayError } from '@sahelpay/sdk';

try {
  const payment = await sahelpay.payments.create({ ... });
} catch (error) {
  if (error instanceof SahelPayError) {
    console.log(error.code);    // 'INVALID_AMOUNT'
    console.log(error.message); // 'Montant minimum: 100 FCFA'
  }
}
```

## Informations de Routing

Chaque paiement retourne des informations sur le routing utilisé (pour monitoring) :

```typescript theme={null}
const payment = await sahelpay.payments.create({ ... });

console.log(payment.gateway_used);    // Identifiant technique interne
console.log(payment.routing_reason);  // Explication du routing choisi
```

<Note>
  Ces champs sont **informatifs uniquement** pour le monitoring. Le choix du routing est automatique et transparent pour vous.
</Note>

## Capabilities

Vérifiez les fonctionnalités disponibles pour chaque méthode de paiement :

```typescript theme={null}
import { hasCapability, getMethodsWithCapability } from '@sahelpay/sdk';

// Vérifier si Orange Money supporte les payouts
hasCapability('ORANGE_MONEY', 'payouts'); // true

// Lister les méthodes avec QR code natif
getMethodsWithCapability('qr_code'); // ['WAVE']
```

## Paiement par Carte

Pour les paiements par carte, les champs `customer_name` et `customer_email` sont **requis** :

```typescript theme={null}
const payment = await sahelpay.payments.create({
  amount: 10000,
  currency: 'XOF',
  payment_method: 'CARD',
  customer_phone: '+22370123456',
  customer_name: 'Mamadou Diallo',      // Requis pour CARD
  customer_email: 'mamadou@example.com', // Requis pour CARD
  return_url: 'https://votre-site.com/checkout/return',
});
```
