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

# Top-Up eSIM

> Add more data to an existing eSIM package

## Overview

Top up an existing eSIM with additional data using top-up packages. This extends the data allowance of an active eSIM without creating a new one.

<Note>
  **Key Requirements:** Top-ups require:

  * `packageType: 'TOPUP'`
  * `packageCode`: TOPUP package code (e.g., "TOPUP\_P3ICIKSE8")
  * `esimId`: The ID of the eSIM to top up (obtained from previous purchase or fetch)
</Note>

<Warning>
  **Two-Step Process:** Like purchases, the top-up API returns a `transactionId`. Query `/api/esim/{transactionId}` to get updated eSIM details with the new data balance.
</Warning>

## Quick Start

<CodeGroup>
  ```javascript JavaScript theme={null}
  async function topUpEsim(esimId, topupPackageCode) {
    // Step 1: Purchase top-up
    const response = await fetch('https://api.vellosim.com/api/esim/buy', {
      method: 'POST',
      headers: {
        'X-API-Key': `API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        packageCode: topupPackageCode,  // TOPUP package code (e.g., TOPUP_P3ICIKSE8)
        paymentMethod: 'WALLET',
        packageType: 'TOPUP',
        esimId: esimId  // ID of the eSIM to top up
      })
    });
    
    const data = await response.json();
    
    if (data.status !== 'SUCCESS') {
      throw new Error('Top-up failed');
    }
    
    // Step 2: Fetch updated eSIM details
    const esimResponse = await fetch(
      `https://api.vellosim.com/api/esim/${data.transactionId}`,
      {
        headers: {
          'X-API-Key': `API_KEY}`
        }
      }
    );
    
    const esimData = await esimResponse.json();
    
    return {
      transactionId: data.transactionId,
      iccid: esimData.iccid,
      dataRemaining: esimData.data_usage_remain,
      totalVolume: esimData.totalVolume,
      validityRemaining: esimData.validity_usage_remain
    };
  }

  // Usage
  const result = await topUpEsim('69125f9f56d7f09edabbaf23', 'TOPUP_P3ICIKSE8');
  console.log('Top-up successful! New data:', result.dataRemaining);
  ```

  ```python Python theme={null}
  import requests

  def topup_esim(esim_id, topup_package_code):
      """Top up an existing eSIM with additional data"""
      headers = {
          'X-API-Key': f' {API_KEY}',
          'Content-Type': 'application/json'
      }
      
      # Step 1: Purchase top-up
      purchase_data = {
          'packageCode': topup_package_code,  # TOPUP package code
          'paymentMethod': 'WALLET',
          'packageType': 'TOPUP',
          'esimId': esim_id  # ID of the eSIM to top up
      }
      
      purchase_response = requests.post(
          'https://api.vellosim.com/api/esim/buy',
          headers=headers,
          json=purchase_data
      )
      
      purchase_result = purchase_response.json()
      
      if purchase_result['status'] != 'SUCCESS':
          raise Exception('Top-up failed')
      
      transaction_id = purchase_result['transactionId']
      
      # Step 2: Fetch updated eSIM details
      esim_response = requests.get(
          f'https://api.vellosim.com/api/esim/{transaction_id}',
          headers=headers
      )
      
      esim_data = esim_response.json()
      
      return {
          'transactionId': transaction_id,
          'iccid': esim_data['iccid'],
          'dataRemaining': esim_data['data_usage_remain'],
          'totalVolume': esim_data['totalVolume'],
          'validityRemaining': esim_data['validity_usage_remain']
      }

  # Usage
  result = topup_esim('69125f9f56d7f09edabbaf23', 'TOPUP_P3ICIKSE8')
  print(f"Top-up successful! New data: {result['dataRemaining']}")
  ```

  ```php PHP theme={null}
  <?php
  function topUpEsim($esimId, $topupPackageCode) {
      $apiKey = 'YOUR_API_KEY';
      $headers = [
          'X-API-Key: ' . $apiKey,
          'Content-Type: application/json'
      ];
      
      // Step 1: Purchase top-up
      $purchaseData = [
          'packageCode' => $topupPackageCode,  // TOPUP package code
          'paymentMethod' => 'WALLET',
          'packageType' => 'TOPUP',
          'esimId' => $esimId  // ID of the eSIM to top up
      ];
      
      $ch = curl_init('https://api.vellosim.com/api/esim/buy');
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($purchaseData));
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      
      $purchaseResponse = curl_exec($ch);
      $purchaseResult = json_decode($purchaseResponse, true);
      curl_close($ch);
      
      if ($purchaseResult['status'] !== 'SUCCESS') {
          throw new Exception('Top-up failed');
      }
      
      $transactionId = $purchaseResult['transactionId'];
      
      // Step 2: Fetch updated eSIM details
      $ch = curl_init("https://api.vellosim.com/api/esim/{$transactionId}");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      
      $esimResponse = curl_exec($ch);
      $esimData = json_decode($esimResponse, true);
      curl_close($ch);
      
      return [
          'transactionId' => $transactionId,
          'iccid' => $esimData['iccid'],
          'dataRemaining' => $esimData['data_usage_remain'],
          'totalVolume' => $esimData['totalVolume'],
          'validityRemaining' => $esimData['validity_usage_remain']
      ];
  }

  // Usage
  $result = topUpEsim('69125f9f56d7f09edabbaf23', 'TOPUP_P3ICIKSE8');
  echo "Top-up successful! New data: " . $result['dataRemaining'];
  ?>
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  type TopUpRequest struct {
      PackageCode   string `json:"packageCode"`
      PaymentMethod string `json:"paymentMethod"`
      PackageType   string `json:"packageType"`
      EsimID        string `json:"esimId"`
  }
      PaymentMethod string `json:"paymentMethod"`
      PackageType   string `json:"packageType"`
  }

  type TopUpResponse struct {
      Status        string `json:"status"`
      TransactionID string `json:"transactionId"`
  }

  type EsimDetails struct {
      ICCID             string `json:"iccid"`
      DataUsageRemain   int64  `json:"data_usage_remain"`
      TotalVolume       int64  `json:"totalVolume"`
      ValidityUsageRemain int  `json:"validity_usage_remain"`
  }

  func topUpEsim(apiKey, esimID, topupPackageCode string) (*EsimDetails, error) {
      // Step 1: Purchase top-up
      reqBody := TopUpRequest{
          PackageCode:   topupPackageCode,
          PaymentMethod: "WALLET",
          PackageType:   "TOPUP",
          EsimID:        esimID,
      }
      
      jsonData, _ := json.Marshal(reqBody)
      
      client := &http.Client{}
      req, _ := http.NewRequest("POST", "https://api.vellosim.com/api/esim/buy", 
          bytes.NewBuffer(jsonData))
      req.Header.Set("X-API-Key", apiKey)
      req.Header.Set("Content-Type", "application/json")
      
      resp, err := client.Do(req)
      if err != nil {
          return nil, err
      }
      defer resp.Body.Close()
      
      body, _ := io.ReadAll(resp.Body)
      
      var purchaseResult TopUpResponse
      json.Unmarshal(body, &purchaseResult)
      
      if purchaseResult.Status != "SUCCESS" {
          return nil, fmt.Errorf("top-up failed")
      }
      
      // Step 2: Fetch updated eSIM details
      req2, _ := http.NewRequest("GET", 
          "https://api.vellosim.com/api/esim/"+purchaseResult.TransactionID, nil)
      req2.Header.Set("X-API-Key", apiKey)
      
      resp2, err := client.Do(req2)
      if err != nil {
          return nil, err
      }
      defer resp2.Body.Close()
      
      body2, _ := io.ReadAll(resp2.Body)
      
      var esimDetails EsimDetails
      json.Unmarshal(body2, &esimDetails)
      
      return &esimDetails, nil
  }

  func main() {
      result, err := topUpEsim("YOUR_API_KEY", "69125f9f56d7f09edabbaf23", "TOPUP_P3ICIKSE8")
      if err != nil {
          fmt.Println("Top-up failed:", err)
          return
      }
      fmt.Printf("Top-up successful! New data: %d bytes\n", result.DataUsageRemain)
  }
  ```
</CodeGroup>

## Request Body

| Field           | Type   | Required | Description                                                |
| --------------- | ------ | -------- | ---------------------------------------------------------- |
| `packageCode`   | string | Yes      | TOPUP package identifier (e.g., "TOPUP\_P3ICIKSE8")        |
| `paymentMethod` | string | Yes      | Must be "WALLET" for API users                             |
| `packageType`   | string | Yes      | Must be "TOPUP" for top-up purchases                       |
| `esimId`        | string | Yes      | ID of the eSIM to top up (from purchase or fetch response) |

<Note>
  **Finding TOPUP Packages:** Query `/api/esim/packages?regionCode=US&type=TOPUP&packageCode=CKH533` to get available top-up packages. Top-up package codes are prefixed with `TOPUP_`.
</Note>

## Successful Response

**Step 1: Purchase Response**

```json theme={null}
{
  "transactionId": "esim_1762812333247_7046",
  "status": "SUCCESS",
  "package": {
    "packageCode": "TOPUP_P3ICIKSE8",
    "name": "United States 10GB 30Days",
    "price": 14640,
    "volume": 0,
    "duration": 0,
    "currencyCode": "NGN"
  }
}
```

**Step 2: Updated eSIM Details**

```json theme={null}
{
  "iccid": "8997250230000286674",
  "transactionId": "esim_1762812333247_7046",
  "totalVolume": 11261296640,
  "data_usage_remain": 11261296640,
  "validity_usage_remain": 37,
  "expiredTime": "2026-05-09T21:56:47.000Z",
  "packageDetails": {
    "name": "United States 10GB 30Days",
    "code": "CKH533",
    "volume": 10737418240
  }
}
```

<Note>
  The `totalVolume` and `data_usage_remain` are updated to reflect the added data. Values are in bytes.
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Purchase eSIM" icon="shopping-cart" href="/guides/purchase-esim">
    Buy a new eSIM package
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/purchase/buy">
    Complete API documentation
  </Card>
</CardGroup>
