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

# SDKs & Libraries

> Integrate Carbon Business API effortlessly using our official SDKs and libraries for various programming languages.

The Carbon Business API SDKs provide a convenient way to integrate with our platform, offering pre-built functions for common operations like account creation, payouts, and transaction management.

## Node.js/JavaScript SDK

Our official Node.js SDK simplifies integration with the Carbon Business API, providing TypeScript support and comprehensive error handling.

### Installation

Install the SDK via npm:

```bash theme={null}
npm install carbon-baas-sdk
```

<Info>
  Requires Node.js 14.0 or higher for optimal compatibility.
</Info>

### Configuration

Initialize the SDK with your API key and environment mode.

<Note>
  Always use environment variables to store your API keys securely. Never hardcode them in your source code.
</Note>

#### Environment Setup

```bash theme={null}
# .env file
CARBON_API_KEY=your_api_key_here
CARBON_ENV=sandbox  # or 'live' for production
```

#### CommonJS Example

```javascript theme={null}
const carbon = require('carbon-baas-sdk');

// Initialize the SDK
carbon.initialize(process.env.CARBON_API_KEY, process.env.CARBON_ENV);
```

#### ES6/TypeScript Example

```typescript theme={null}
import { CarbonSDK } from 'carbon-baas-sdk';

// Initialize the SDK
const carbon = new CarbonSDK({
  apiKey: process.env.CARBON_API_KEY!,
  environment: process.env.CARBON_ENV as 'sandbox' | 'live'
});
```

## Core Operations

### Account Management

<AccordionGroup>
  <Accordion title="Create Collection Account">
    ```javascript theme={null}
    // Create a collection sub-account
    const collectionAccount = await carbon.createAccount({
      accountType: 'static',
      thirdParty: false,
      accountName: 'My Collections'
    });

    console.log('Account Number:', collectionAccount.data.account.account_number);
    ```
  </Accordion>

  <Accordion title="Create Customer-Linked Account">
    ```javascript theme={null}
    // First create a customer
    const customer = await carbon.createCustomer({
      email: 'customer@example.com',
      phone: '08012345678',
      firstName: 'John',
      lastName: 'Doe',
      bvn: '12345678901'
    });

    // Then create account linked to customer
    const businessAccount = await carbon.createAccount({
      accountType: 'static',
      thirdParty: true,
      customerId: customer.data.id
    });
    ```
  </Accordion>

  <Accordion title="Fetch Account Details">
    ```javascript theme={null}
    try {
      const account = await carbon.getAccount('1234567890');
      console.log('Account Details:', account.data);
    } catch (error) {
      console.error('Account not found:', error.message);
    }
    ```
  </Accordion>

  <Accordion title="Check Account Balance">
    ```javascript theme={null}
    const balance = await carbon.fetchBalance('1234567890');
    console.log('Available Balance:', balance.data.available_balance);
    ```
  </Accordion>
</AccordionGroup>

### Payouts

<AccordionGroup>
  <Accordion title="Validate Beneficiary Account">
    ```javascript theme={null}
    const validation = await carbon.resolveAccount({
      accountNumber: '0123456789',
      bankCode: '058'
    });

    if (validation.status === 'success') {
      console.log('Account Name:', validation.data.account_name);
    }
    ```
  </Accordion>

  <Accordion title="Create Payout">
    ```javascript theme={null}
    const payout = await carbon.createPayout({
      amount: 50000, // Amount in kobo (₦500)
      source: {
        accountNumber: 'your_account_number'
      },
      beneficiary: {
        bankCode: '058',
        bankName: 'GTBank',
        accountNumber: '0123456789',
        accountName: 'Jane Smith'
      },
      reference: `PAY_${Date.now()}`, // Unique reference
      remark: 'Service payment'
    });

    console.log('Payout Reference:', payout.data.reference);
    ```
  </Accordion>

  <Accordion title="Track Payout Status">
    ```javascript theme={null}
    const status = await carbon.getPayoutStatus('PAY_1737326400123');
    console.log('Payout Status:', status.data.status);
    ```
  </Accordion>
</AccordionGroup>

### Transaction Management

<AccordionGroup>
  <Accordion title="Fetch Transactions">
    ```javascript theme={null}
    const transactions = await carbon.fetchTransactions({
      accountNumber: '1234567890',
      startDate: '2026-01-01',
      endDate: '2026-01-19',
      limit: 50
    });

    console.log('Transaction Count:', transactions.data.length);
    ```
  </Accordion>

  <Accordion title="Verify Transaction">
    ```javascript theme={null}
    const verification = await carbon.verifyTransaction('TXN_REF_123');

    if (verification.data.status === 'successful') {
      console.log('Transaction verified successfully');
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Handling

Implement robust error handling for production applications:

```javascript theme={null}
try {
  const result = await carbon.createPayout(payoutData);
  return result;
} catch (error) {
  if (error.code === 'INSUFFICIENT_BALANCE') {
    console.error('Insufficient funds for payout');
  } else if (error.code === 'INVALID_ACCOUNT') {
    console.error('Invalid beneficiary account details');
  } else if (error.code === 'DUPLICATE_REFERENCE') {
    console.error('Reference already used, generate new one');
  } else {
    console.error('Unexpected error:', error.message);
  }
  
  throw error; // Re-throw for upstream handling
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Environment Configuration">
    * Use environment variables for API keys and configuration
    * Never commit sensitive credentials to version control
    * Use different API keys for sandbox and live environments
  </Accordion>

  <Accordion title="Error Handling">
    * Always implement try-catch blocks for async operations
    * Log errors appropriately for debugging
    * Provide meaningful error messages to users
  </Accordion>

  <Accordion title="Reference Generation">
    * Use unique, timestamp-based references for payouts
    * Keep references under 30 characters
    * Include identifiable prefixes for easier tracking
  </Accordion>

  <Accordion title="Rate Limiting">
    * Implement retry logic with exponential backoff
    * Monitor API usage to stay within limits
    * Cache frequently accessed data when appropriate
  </Accordion>
</AccordionGroup>

## Webhook Integration

Handle webhook events for real-time notifications:

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

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

app.post('/webhook', (req, res) => {
  const signature = req.headers['carbon-signature'];
  const webhookSecret = process.env.CARBON_WEBHOOK_SECRET;
  
  // Verify webhook signature
  const computedSignature = crypto
    .createHmac('sha256', webhookSecret)
    .update(JSON.stringify(req.body))
    .digest('hex');
    
  if (signature === computedSignature) {
    const event = req.body;
    
    switch (event.type) {
      case 'account.incoming-transaction':
        console.log('Payment received:', event.data);
        break;
      case 'payout.successful':
        console.log('Payout completed:', event.data);
        break;
      default:
        console.log('Unknown event type:', event.type);
    }
    
    res.status(200).send('OK');
  } else {
    res.status(401).send('Invalid signature');
  }
});
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Authentication Issues">
    <Warning>
      Ensure you're using the correct API key for your environment (sandbox vs live).
    </Warning>
  </Accordion>

  <Accordion title="Network Errors">
    <Info>
      Implement retry logic for network failures and timeout errors.
    </Info>
  </Accordion>

  <Accordion title="Validation Errors">
    <Note>
      Check that all required fields are provided and account numbers are valid before making API calls.
    </Note>
  </Accordion>
</AccordionGroup>

## Additional Resources

* [Payment Operations Guide](/payment-operations) - Complete workflow examples
* [Webhook Documentation](/webhooks/introduction) - Real-time event handling
* [API Reference](/api-reference/introduction) - Detailed endpoint documentation
* [Environment Setup](/environment) - Sandbox vs Live configuration

<Info>
  For other programming languages or framework-specific integrations, please contact our support team at [sme@getcarbon.co](mailto:sme@getcarbon.co).
</Info>
