# Nass Payment Gateway SDK

A TypeScript/JavaScript SDK for integrating with the Nass Merchant Payment Gateway. This package provides a simple and secure way to process payments using both Portal and Direct API integration methods.

## Features

- 🔒 **Secure authentication** with automatic token management
- 🌐 **Dual integration methods**: Portal and Direct API
- 📝 **Full TypeScript support** with comprehensive type definitions
- 🧪 **UAT environment support** for testing
- ✅ **Production ready** with proper error handling
- 📚 **Comprehensive documentation** and examples

## Installation

```bash
npm install nasspay
```

## Quick Start

### Portal Integration (Recommended for most merchants)

```typescript
import NassPaymentGateway from "nasspay";

const gateway = new NassPaymentGateway({
  username: "your-merchant-username",
  password: "your-merchant-password",
  environment: "UAT", // or 'PRODUCTION'
});

async function processPayment() {
  try {
    // Authenticate
    await gateway.authenticate();

    // Create transaction
    const transaction = await gateway.createPortalTransaction(
      "ORDER-123", // orderId
      "Purchase of goods", // orderDesc
      150.0, // amount
      "368", // currency (Iraqi Dinar)
      "1", // transactionType (1 = sale)
      "https://yoursite.com/success", // backRef (redirect URL)
      "https://yoursite.com/webhook" // notifyUrl (webhook URL)
    );

    // Redirect customer to payment page
    console.log("Redirect customer to:", transaction.data.url);
  } catch (error) {
    console.error("Payment failed:", error);
  }
}
```

### Direct API Integration (For PCI compliant merchants)

```typescript
import NassPaymentGateway from "nasspay";

const gateway = new NassPaymentGateway({
  username: "your-merchant-username",
  password: "your-merchant-password",
  environment: "UAT",
});

async function processDirectPayment() {
  try {
    // Authenticate
    await gateway.authenticate();

    // Step 1: Initiate transaction
    const initResponse = await gateway.createDirectApiTransaction(
      "ORDER-456",
      "Direct payment",
      100.0,
      "368",
      "1"
    );

    // Step 2: Send card details
    const result = await gateway.sendDirectApiCardholderData(
      initResponse.data.pSign,
      initResponse.data.transactionParams.NONCE,
      {
        pan: "4761349999000047",
        expMonth: "12",
        expYear: "25",
        cvc2: "356",
        cardholderName: "John Doe",
      },
      {
        orderId: "ORDER-456",
        amount: "10000", // amount in minor units
        currency: "368",
        transactionType: "1",
        terminalId: initResponse.data.transactionParams.TERMINAL,
        orderDesc: "Direct payment",
        timestamp: initResponse.data.transactionParams.TIMESTAMP,
        backRefUrl: "https://yoursite.com/success",
      }
    );

    console.log("Transaction result:", result);
  } catch (error) {
    console.error("Direct payment failed:", error);
  }
}
```

## Configuration

### Basic Configuration

```typescript
const gateway = new NassPaymentGateway({
  username: "merchant_username",
  password: "merchant_password",
  environment: "UAT", // or 'PRODUCTION'
});
```

### Advanced Configuration (Production)

```typescript
const gateway = new NassPaymentGateway({
  username: "merchant_username",
  password: "merchant_password",
  environment: "PRODUCTION",
  portalBaseUrl: "https://your-prod-gateway.com",
  directApiTransactionUrl: "https://your-prod-direct-api.com",
});
```

## API Reference

### Authentication

#### `authenticate()`

Authenticates the merchant and retrieves an access token.

```typescript
await gateway.authenticate();
```

### Portal Integration

#### `createPortalTransaction(orderId, orderDesc, amount, currency, transactionType, backRef, notifyUrl?)`

Creates a new payment transaction using the Portal method.

**Parameters:**

- `orderId` (string): Unique order identifier
- `orderDesc` (string): Order description
- `amount` (number): Order total amount
- `currency` (string): 3-character ISO currency code (e.g., '368' for Iraqi Dinar)
- `transactionType` (string): Transaction type ('1' for sale)
- `backRef` (string): Frontend redirect URL after payment
- `notifyUrl` (string, optional): Backend webhook URL for callbacks

#### `checkPortalTransactionStatus(orderId)`

Checks the status of a Portal transaction.

### Direct API Integration

#### `createDirectApiTransaction(orderId, orderDesc, amount, currency, transactionType)`

Initiates the first step of a Direct API transaction.

#### `sendDirectApiCardholderData(pSign, nonce, cardDetails, orderDetails)`

Sends cardholder data for Direct API authorization.

#### `checkDirectApiTransactionStatus(orderId)`

Checks the status of a Direct API transaction.


## Error Handling

The SDK includes comprehensive error handling for common scenarios:

```typescript
try {
  await gateway.authenticate();
  const transaction = await gateway.createPortalTransaction(/* ... */);
} catch (error) {
  if (error.code === 401) {
    console.error("Authentication failed");
  } else if (error.code === 400) {
    console.error("Invalid parameters:", error.message);
  } else {
    console.error("Unexpected error:", error);
  }
}
```

## Webhook/Callback Handling

When using Portal integration, implement a webhook endpoint to receive transaction status updates:

```typescript
// Express.js example
app.post("/webhook/nass-payment", (req, res) => {
  const callbackData = req.body;

  // Verify and process the callback
  console.log("Payment status:", callbackData.statusMsg);
  console.log("Order ID:", callbackData.orderId);
  console.log("Amount:", callbackData.amount);

  res.status(200).send("OK");
});
```

## Security Considerations

- **Never store card data** - Use Portal integration for non-PCI environments
- **Validate all webhooks** - Verify signatures and data integrity
- **Use HTTPS** - Always use secure connections in production
- **Store credentials securely** - Use environment variables for sensitive data

## Environment Variables

```bash
NASS_USERNAME=your_merchant_username
NASS_PASSWORD=your_merchant_password
NASS_ENVIRONMENT=UAT
```

```typescript
const gateway = new NassPaymentGateway({
  username: process.env.NASS_USERNAME!,
  password: process.env.NASS_PASSWORD!,
  environment: process.env.NASS_ENVIRONMENT as "UAT" | "PRODUCTION",
});
```

## Support

For technical support or questions about the Nass Payment Gateway API, contact your account manager or the Nass support team.

## License

MIT

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request

## Changelog

### v1.0.0

- Initial release
- Portal integration support
- Direct API integration support
- TypeScript definitions
- Comprehensive test coverage
