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

# Authentication

> Learn how to authenticate with the Orsunpay API using API keys and security headers

# Authentication

Orsunpay uses API keys to authenticate requests. Your API keys carry many privileges, so keep them secure and never share them in publicly accessible areas such as GitHub, client-side code, and so forth.

## API Keys

All API requests must be authenticated using your secret API key in the Authorization header.

### Key Format

API keys follow this format:

* **Sandbox**: `sk_test_...`
* **Production**: `sk_live_...`

### Authentication Header

Include your API key in the Authorization header as a Bearer token:

```bash theme={null}
curl "https://api.orsunpay.com/v1/transactions" \
  -H "Authorization: Bearer sk_live_your_api_key_here"
```

<Warning>
  **Never expose your secret API key in client-side code.** Use it only on your secure backend servers.
</Warning>

## Required Headers

### Authorization

Every API request must include the Authorization header:

```http theme={null}
Authorization: Bearer sk_live_your_api_key_here
```

### Content-Type

For requests with a request body, specify the content type:

```http theme={null}
Content-Type: application/json
```

### Idempotency Key

For critical operations (creating transactions, refunds), use the `Idempotency-Key` header to prevent duplicate processing:

```http theme={null}
Idempotency-Key: your-unique-key-here
```

<Tip>
  Use a unique identifier like UUID v4 for each operation. If you retry the same request with the same idempotency key within 24 hours, you'll receive the original response.
</Tip>

## API Versioning

All API endpoints use versioning in the URL path:

```
https://api.orsunpay.com/v1/...
```

Current version is `v1`. We maintain backward compatibility and will announce any breaking changes well in advance.

## Example Authentication

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.orsunpay.com/v1/merchants/me" \
    -H "Authorization: Bearer sk_live_your_api_key_here" \
    -H "Content-Type: application/json"
  ```

  ```javascript JavaScript (Fetch) theme={null}
  const response = await fetch('https://api.orsunpay.com/v1/merchants/me', {
    headers: {
      'Authorization': 'Bearer sk_live_your_api_key_here',
      'Content-Type': 'application/json'
    }
  });

  const merchant = await response.json();
  console.log(merchant);
  ```

  ```javascript Node.js (Axios) theme={null}
  const axios = require('axios');

  const client = axios.create({
    baseURL: 'https://api.orsunpay.com/v1',
    headers: {
      'Authorization': 'Bearer sk_live_your_api_key_here',
      'Content-Type': 'application/json'
    }
  });

  const response = await client.get('/merchants/me');
  console.log(response.data);
  ```
</CodeGroup>

## Creating a Transaction with Authentication

Here's a complete example of creating a transaction with proper authentication:

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://api.orsunpay.com/v1/transactions" \
    -X POST \
    -H "Authorization: Bearer sk_live_your_api_key_here" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $(uuidgen)" \
    -d '{
      "merchantId": "mr_clkj3h2n0000qjr8x4c5h6e7b",
      "paymentMethod": "card",
      "buyerId": "customer_12345",
      "orderId": "order_67890",
      "amount": 5000,
      "currency": "USD",
      "successUrl": "https://yoursite.com/success",
      "failureUrl": "https://yoursite.com/failure",
      "returnUrl": "https://yoursite.com/return",
      "callbackUrl": "https://yoursite.com/webhooks/orsunpay",
      "customer": {
        "email": "customer@example.com",
        "firstName": "John",
        "lastName": "Doe"
      }
    }'
  ```

  ```javascript JavaScript (Fetch) theme={null}
  const response = await fetch('https://api.orsunpay.com/v1/transactions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk_live_your_api_key_here',
      'Content-Type': 'application/json',
      'Idempotency-Key': crypto.randomUUID()
    },
    body: JSON.stringify({
      merchantId: 'mr_clkj3h2n0000qjr8x4c5h6e7b',
      paymentMethod: 'card',
      buyerId: 'customer_12345',
      orderId: 'order_67890',
      amount: 5000,
      currency: 'USD',
      successUrl: 'https://yoursite.com/success',
      failureUrl: 'https://yoursite.com/failure',
      returnUrl: 'https://yoursite.com/return',
      callbackUrl: 'https://yoursite.com/webhooks/orsunpay',
      customer: {
        email: 'customer@example.com',
        firstName: 'John',
        lastName: 'Doe'
      }
    })
  });

  const transaction = await response.json();
  console.log(transaction);
  ```

  ```javascript Node.js (Axios) theme={null}
  const axios = require('axios');
  const { v4: uuidv4 } = require('uuid');

  const client = axios.create({
    baseURL: 'https://api.orsunpay.com/v1',
    headers: {
      'Authorization': 'Bearer sk_live_your_api_key_here',
      'Content-Type': 'application/json'
    }
  });

  const response = await client.post('/transactions', {
    merchantId: 'mr_clkj3h2n0000qjr8x4c5h6e7b',
    paymentMethod: 'card',
    buyerId: 'customer_12345',
    orderId: 'order_67890',
    amount: 5000,
    currency: 'USD',
    successUrl: 'https://yoursite.com/success',
    failureUrl: 'https://yoursite.com/failure',
    returnUrl: 'https://yoursite.com/return',
    callbackUrl: 'https://yoursite.com/webhooks/orsunpay',
    customer: {
      email: 'customer@example.com',
      firstName: 'John',
      lastName: 'Doe'
    }
  }, {
    headers: {
      'Idempotency-Key': uuidv4()
    }
  });

  console.log(response.data);
  ```
</CodeGroup>

## Environment-Specific Keys

Use different API keys for different environments:

| Environment    | API Key Prefix | Base URL                              |
| -------------- | -------------- | ------------------------------------- |
| **Sandbox**    | `sk_test_...`  | `https://sandbox-api.orsunpay.com/v1` |
| **Production** | `sk_live_...`  | `https://api.orsunpay.com/v1`         |

<Note>
  Sandbox transactions use test payment providers and don't process real money. Always test your integration thoroughly in sandbox before going live.
</Note>

## Webhook Authentication

For incoming webhooks from Orsunpay, verify the signature using your merchant's private key:

### Signature Verification

Webhooks include an `X-Orsunpay-Signature` header with HMAC-SHA256 signature:

```javascript theme={null}
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
  
  return `sha256=${expectedSignature}` === signature;
}

// Usage
const isValid = verifyWebhookSignature(
  req.body, 
  req.headers['x-orsunpay-signature'], 
  merchantPrivateKey
);

if (!isValid) {
  throw new Error('Invalid webhook signature');
}
```

<Warning>
  Always verify webhook signatures to ensure requests are coming from Orsunpay and haven't been tampered with.
</Warning>

## Error Responses

Authentication errors return specific HTTP status codes:

### 401 Unauthorized

Missing or invalid API key:

```json theme={null}
{
  "error": {
    "code": "authentication_required",
    "message": "No API key provided"
  }
}
```

### 403 Forbidden

Valid API key but insufficient permissions:

```json theme={null}
{
  "error": {
    "code": "insufficient_permissions", 
    "message": "API key does not have permission for this operation"
  }
}
```

## Security Best Practices

### Server-Side Only

<Warning>
  **Critical**: Never use secret API keys in client-side code (JavaScript, mobile apps, etc.). They should only be used on your secure backend servers.
</Warning>

### Key Management

* **Rotate keys regularly** for enhanced security
* **Use environment variables** to store keys, never hardcode them
* **Implement proper access controls** for key storage
* **Monitor API key usage** for unusual patterns

### HTTPS Required

All API requests must use HTTPS. HTTP requests will be rejected:

```bash theme={null}
# ✅ Correct - uses HTTPS
curl "https://api.orsunpay.com/v1/merchants/me"

# ❌ Incorrect - uses HTTP (will be rejected)
curl "http://api.orsunpay.com/v1/merchants/me"
```

### Request Logging

For security and debugging, log API requests (but never log sensitive data):

```javascript theme={null}
// ✅ Good - log request metadata
console.log('API request:', {
  method: 'POST',
  url: '/transactions',
  timestamp: new Date().toISOString(),
  idempotencyKey: headers['idempotency-key']
});

// ❌ Bad - logging sensitive data
console.log('API key:', apiKey); // Never do this
console.log('Request body:', requestBody); // Be careful with PII
```

## Testing Your Authentication

Use this simple test to verify your authentication setup:

<CodeGroup>
  ```bash cURL theme={null}
  # Test authentication
  curl "https://api.orsunpay.com/v1/merchants/me" \
    -H "Authorization: Bearer your_api_key_here"

  # Expected response
  {
    "id": "mr_clkj3h2n0000qjr8x4c5h6e7b",
    "name": "Your Merchant Name",
    "domain": "your-domain.com",
    "isActive": true
  }
  ```

  ```javascript JavaScript theme={null}
  async function testAuth() {
    try {
      const response = await fetch('https://api.orsunpay.com/v1/merchants/me', {
        headers: {
          'Authorization': 'Bearer your_api_key_here'
        }
      });

      if (response.ok) {
        const merchant = await response.json();
        console.log('Authentication successful:', merchant.name);
      } else {
        console.error('Authentication failed:', response.status);
      }
    } catch (error) {
      console.error('Request failed:', error);
    }
  }

  testAuth();
  ```
</CodeGroup>

## Next Steps

Now that you have authentication set up, you can:

<CardGroup cols={2}>
  <Card title="Explore API Endpoints" icon="code-branch" href="/api/transactions">
    Learn about our core API endpoints and start processing transactions.
  </Card>

  <Card title="Set Up Webhooks" icon="webhook" href="/api/webhooks">
    Configure webhook endpoints to receive real-time payment notifications.
  </Card>
</CardGroup>
