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

# End-to-end example

> An end-to-end flow, from user registration to charging completion.

## User Journey

This guide demonstrates a complete user journey through the Cariqa Connect API, showing how all the endpoints work together to deliver a seamless charging experience.

## Flow Overview

1. **User Registration** - Create user account
2. **Payment Setup** - Add and configure payment method via Stripe
3. **Station Discovery** - Find nearby charging stations
4. **Start Charging** - Initiate a charging session
5. **Monitor Session** - Track charging progress
6. **Stop Charging** - End session and get receipt

***

## 1. User Registration

First, create a user account in the system:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://connect.cariqa.com/api/v1/users/" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "email": "alice@example.com",
      "locale": "en"
    }'
  ```

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

  headers = {
      "Authorization": "Bearer YOUR_API_TOKEN",
      "Content-Type": "application/json"
  }

  user_data = {
      "email": "alice@example.com",
      "locale": "en"
  }

  response = requests.post(
      "https://connect.cariqa.com/api/v1/users/",
      headers=headers,
      json=user_data
  )
  user = response.json()
  user_id = user["id"]  # Save this for subsequent calls
  ```

  ```javascript JavaScript theme={null}
  const headers = {
    'Authorization': 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json'
  };

  const userData = {
    email: 'alice@example.com',
    locale: 'en'
  };

  const response = await fetch('https://connect.cariqa.com/api/v1/users/', {
    method: 'POST',
    headers,
    body: JSON.stringify(userData)
  });

  const user = await response.json();
  const userId = user.id; // Save this for subsequent calls
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "id": "123",
  "email": "alice@example.com",
  "locale": "en"
}
```

***

## 2. Payment Method Setup

### 2.1 Create Setup Intent

Get a Stripe setup intent to securely collect payment information:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://connect.cariqa.com/api/v1/users/123/setup-intents/?pm_type=card" \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

  ```python Python theme={null}
  response = requests.get(
      f"https://connect.cariqa.com/api/v1/users/{user_id}/setup-intents/?pm_type=card",
      headers=headers
  )
  setup_intent = response.json()
  client_secret = setup_intent["client_secret"]
  ```

  ```javascript JavaScript theme={null}
  const setupResponse = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/setup-intents/?pm_type=card`, {
    headers
  });
  const setupIntent = await setupResponse.json();
  const clientSecret = setupIntent.client_secret;
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "client_secret": "seti_1ABC123_secret_DEF456"
}
```

### 2.2 Frontend Stripe Integration

<Warning>
  The following Stripe integration MUST happen on your frontend for PSD2/SCA compliance.
</Warning>

Follow the [Payment Frontend Setup](/payments-frontend-setup) guide to confirm the Setup Intent on the client side (iOS, Android, Web).

### 2.3 Verify Payment Method Added

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://connect.cariqa.com/api/v1/users/123/payment-methods/" \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

  ```python Python theme={null}
  response = requests.get(
      f"https://connect.cariqa.com/api/v1/users/{user_id}/payment-methods/",
      headers=headers
  )
  payment_methods = response.json()
  default_pm = next(pm for pm in payment_methods["results"] if pm["is_default"])
  payment_method_id = default_pm["id"]
  ```

  ```javascript JavaScript theme={null}
  const pmResponse = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/payment-methods/`, {
    headers
  });
  const paymentMethods = await pmResponse.json();
  const defaultPm = paymentMethods.results.find(pm => pm.is_default);
  const paymentMethodId = defaultPm.id;
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "count": 1,
  "next": null,
  "previous": null,
  "results": [
    {
      "id": "pm_1TD1LuHtgZxQ1KXxNj5sKkKM",
      "default": true,
      "type": "card",
      "card": {
        "brand": "visa",
        "last4": "4242",
        "expiration_date": "04/2044",
        "cardholder_name": null
      },
      "created_at": "2026-03-20T11:36:30Z"
    }
  ]
}
```

***

## 3. Station Discovery

Find nearby charging stations:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://connect.cariqa.com/api/v1/stations/around/?latitude=49.630383&longitude=8.368902&distance=10" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json"
  ```

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

  headers = {
      "Authorization": "Bearer YOUR_API_TOKEN",
      "Content-Type": "application/json"
  }

  response = requests.get(
      "https://connect.cariqa.com/api/v1/stations/around/",
      headers=headers,
      params={
          "latitude": 49.630383,
          "longitude": 8.368902,
          "distance": 10
      }
  )
  stations = response.json()
  chosen_station = stations["results"][0]  # Pick first available station
  evse_id = chosen_station["evses"][0]["evse_id"]  # Pick first available EVSE
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://connect.cariqa.com/api/v1/stations/around/?latitude=49.630383&longitude=8.368902&distance=10', {
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json'
    }
  });

  const stations = await response.json();
  const chosenStation = stations.results[0]; // Pick first available station
  const evseId = chosenStation.evses[0].evse_id; // Pick first available EVSE
  ```
</CodeGroup>

**Response (partial):**

```json expandable theme={null}
{
    "id": "b475f4c35249ae698157660941050322",
    "name": "EVA Charge",
    "speed": "slow",
    "address": "Ludwigstraße, 9, 67547, Worms",
    "status": "free",
    "coordinates": {
      "latitude": "49.630383",
      "longitude": "8.368902"
    },
    "opening_times": {
      "twentyfourseven": true,
      "regular_hours": []
    },
    "operator": {
      "name": "EVA Charge",
      "contact": {
        "phone": "+4971134214480"
      }
    },
    "evses": [
      {
        "evse_id": "DE*CIQ*EELDF6XWZU41P*2",
        "status": "AVAILABLE"
      },
      {
        "evse_id": "DE*CIQ*EWBNHHLM82TLA*2",
        "status": "AVAILABLE"
      },
      {
        "evse_id": "DE*CIQ*EELDF6XWZU41P*1",
        "status": "AVAILABLE"
      },
      {
        "evse_id": "DE*CIQ*EWBNHHLM82TLA*1",
        "status": "CHARGING"
      }
    ],
    "last_updated": "2026-04-02T10:42:22Z",
    "amenities": [],
    "is_partner": true,
    "price_groups": [
      {
        "type": "IEC_62196_T2",
        "power": 22,
        "evse_ids": [
          "DE*CIQ*EELDF6XWZU41P*2",
          "DE*CIQ*EWBNHHLM82TLA*2",
          "DE*CIQ*EELDF6XWZU41P*1",
          "DE*CIQ*EWBNHHLM82TLA*1"
        ],
        "prices": {
          "time_price": null,
          "kwh_price": {
            "MONDAY": [
              {
                "time_from": "00:00",
                "time_to": "01:00",
                "date_from": "2025-12-17",
                "date_to": null,
                "gross_price": "0.1950",
                "user_facing_price": "0.23",
                "grace_period_minutes": null,
                "tax": 19,
                "blocking_cap": null
              },
			  ... 
            ]
          },
          "blocking_fee": {
            "ALL": [
              {
                "time_from": null,
                "time_to": null,
                "date_from": "2025-12-17",
                "date_to": null,
                "gross_price": "4.02",
                "user_facing_price": "0.08",
                "grace_period_minutes": 0,
                "tax": 19,
                "blocking_cap": null
              }
            ]
          },
          "session_fee": null,
          "starting_fee": null
        },
        "local_datetime": "2026-04-02T12:42:22.671636+02:00",
        "currency": "eur",
        "pre_authorization_amount": "30.00",
        "is_fallback": false
      }
    ],
    "logo_url": "https://storage.googleapis.com/cariqa-cpo-logos/custom_evacharge_dev_station_logo.png?generation=1766404007574021&md5_hash=e1e6197d26b8de242509afbbdd66a71a&size=4150"
}
```

***

## 4. Start Charging Session

Initiate charging with the selected EVSE and payment method:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://connect.cariqa.com/api/v1/users/123/charging/start/" \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "evse_id": "DE*CIQ*EELDF6XWZU41P*2",
      "payment_method_id": "pm_1TD1LuHtgZxQ1KXxNj5sKkKM"
    }'
  ```

  ```python Python theme={null}
  start_data = {
      "evse_id": evse_id,
      "payment_method_id": payment_method_id
  }

  response = requests.post(
      f"https://connect.cariqa.com/api/v1/users/{user_id}/charging/start/",
      headers=headers,
      json=start_data
  )
  session_start = response.json()
  session_id = session_start["id"]
  ```

  ```javascript JavaScript theme={null}
  const startData = {
    evse_id: evseId,
    payment_method_id: paymentMethodId
  };

  const startResponse = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/charging/start/`, {
    method: 'POST',
    headers,
    body: JSON.stringify(startData)
  });

  const sessionStart = await startResponse.json();
  const sessionId = sessionStart.id;
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "id": "ab7ae756-b663-43b9-a025-40c51dd503d9",
  "start_time": "2026-04-02T13:51:18.754610Z",
  "end_time": null,
  "duration": 0,
  "consumed_energy": "0.000",
  "is_active": true,
  "evse_id": "DE*CIQ*EELDF6XWZU41P*2",
  "station_info": {
    "station_name": "EVA Charge",
    "station_address": "Ludwigstraße, 9, 67547, Worms",
    "country": "DE",
    "station_speed": "slow",
    "connector_standard": "IEC_62196_T2",
    "connector_power": 22,
    "support_phone": "+4971134214480",
    "latitude": "49.630383",
    "longitude": "8.368902"
  },
  "is_partner": true,
  "logo_url": "https://storage.googleapis.com/cariqa-cpo-logos/evacharge.png?generation=1739874740770603&md5_hash=8dcf9c9d17149760b1c9033218ed1c19&size=11759",
  "user_facing_session_prices": {
    "kwh_price": "0.54",
    "time_price": null,
    "session_fee": null,
    "blocking_fee": null,
    "starting_fee": null,
    "grace_period_minutes": null,
    "blocking_cap": null,
    "currency": "eur"
  },
  "session_cost": null,
  "rates": null
}
```

***

## 5. Monitor Charging Session

Poll the session status to track progress:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://connect.cariqa.com/api/v1/users/123/charging-sessions/ab7ae756-b663-43b9-a025-40c51dd503d9/" \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

  ```python Python theme={null}
  # Poll session status every 30 seconds
  import time

  def monitor_session(user_id, session_id):
      while True:
          response = requests.get(
              f"https://connect.cariqa.com/api/v1/users/{user_id}/charging-sessions/{session_id}/",
              headers=headers
          )
          session = response.json()
          
          print(f"Status: {session['is_active']}")
          print(f"Energy: {session.get('consumed_energy', 0)} kWh")
          print(f"Duration: {session.get('duration', 0)} seconds")
          
          if not session["is_active"]:
              return session
              
          time.sleep(30)  # Wait 30 seconds before next check

  # Start monitoring
  final_session = monitor_session(user_id, session_id)
  ```

  ```javascript JavaScript theme={null}
  // Monitor session with polling
  const monitorSession = async (userId, sessionId) => {
    while (true) {
      const response = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/charging-sessions/${sessionId}/`, {
        headers
      });
      
      const session = await response.json();
      
      console.log(`Status: ${session.is_active}`);
      console.log(`Energy: ${session.consumed_energy || 0} kWh`);
      console.log(`Duration: ${session.duration || 0} seconds`);
      
      if (!session.is_active) {
    		return session;
  	}
      
      // Wait 30 seconds before next check
      await new Promise(resolve => setTimeout(resolve, 30000));
    }
  };

  // Start monitoring
  const finalSession = await monitorSession(userId, sessionId);
  ```
</CodeGroup>

**Response (during charging):**

```json theme={null}
{
  "id": "ab7ae756-b663-43b9-a025-40c51dd503d9",
  "start_time": "2024-03-24T14:30:00Z",
  "duration": 45,
  "consumed_energy": "12.50",
  "is_active": true,
  "evse_id": "DE*CIQ*EELDF6XWZU41P*2",
  ...
}
```

***

## 6. Stop Charging Session

When charging is complete, stop the session:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://connect.cariqa.com/api/v1/users/123/charging/stop/ab7ae756-b663-43b9-a025-40c51dd503d9/" \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

  ```python Python theme={null}
  response = requests.post(
      f"https://connect.cariqa.com/api/v1/users/{user_id}/charging/stop/{session_id}/",
      headers=headers
  )
  stop_result = response.json()
  ```

  ```javascript JavaScript theme={null}
  const stopResponse = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/charging/stop/${sessionId}/`, {
    method: 'POST',
    headers
  });

  const stopResult = await stopResponse.json();
  ```
</CodeGroup>

**Response:**

```http theme={null}
204
```

***

## 7. Get completed charging session

Retrieve the complete session details with final costs:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://connect.cariqa.com/api/v1/users/123/charging-sessions/ab7ae756-b663-43b9-a025-40c51dd503d9/" \
    -H "Authorization: Bearer YOUR_API_TOKEN"
  ```

  ```python Python theme={null}
  response = requests.get(
      f"https://connect.cariqa.com/api/v1/users/{user_id}/charging-sessions/{session_id}/",
      headers=headers
  )
  final_receipt = response.json()

  # Print receipt summary
  print(f"Charging Session Complete!")
  print(f"Energy consumed: {final_receipt['consumed_energy']} kWh")
  print(f"Duration: {final_receipt['duration']} minutes")
  print(f"Total cost: €{final_receipt['payg_summary']['invoice_summary']}")
  print(f"Invoice URL: {final_receipt['payg_summary']['invoice_download']}")
  ```

  ```javascript JavaScript theme={null}
  const receiptResponse = await fetch(`https://connect.cariqa.com/api/v1/users/${userId}/charging-sessions/${sessionId}/`, {
    headers
  });

  const finalReceipt = await receiptResponse.json();

  // Display receipt summary
  console.log('Charging Session Complete!');
  console.log(`Energy consumed: ${finalReceipt.consumed_energy} kWh`);
  console.log(`Duration: ${finalReceipt.duration} minutes`);
  console.log(`Total cost: €${finalReceipt.payg_summary.invoice_summary}`);
  console.log(`Invoice URL: ${finalReceipt.payg_summary.invoice_download}`);
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "id": "ab7ae756-b663-43b9-a025-40c51dd503d9",
  "start_time": "2026-04-02T13:51:18.754610Z",
  "end_time": "2026-04-02T13:51:28.754611Z",
  "duration": 10,
  "consumed_energy": "10.000",
  "is_active": false,
  "evse_id": "DE*CIQ*EELDF6XWZU41P*2",
  "station_info": {
    "station_name": "EVA Charge",
    "station_address": "Ludwigstraße, 9, 67547, Worms",
    "country": "DE",
    "station_speed": "slow",
    "connector_standard": "IEC_62196_T2",
    "connector_power": 22,
    "support_phone": "+4971134214480",
    "latitude": "49.630383",
    "longitude": "8.368902"
  },
  "is_partner": true,
  "logo_url": "https://storage.googleapis.com/cariqa-cpo-logos/evacharge.png?generation=1739874740770603&md5_hash=8dcf9c9d17149760b1c9033218ed1c19&size=11759",
  "user_facing_session_prices": {
    "kwh_price": "0.54",
    "time_price": null,
    "session_fee": null,
    "blocking_fee": null,
    "starting_fee": null,
    "grace_period_minutes": null,
    "blocking_cap": null,
    "currency": "eur"
  },
  "session_cost": {
    "kwh_cost": "5.39",
    "time_cost": "0.00",
    "session_fee_cost": "0.00",
    "blocking_fee_cost": "0.00",
    "starting_fee_cost": "0.00",
    "invoice_download": "https://connect.cariqa.com/download/?<params>",
    "invoice_vat": "0.86",
    "invoice_summary": "5.39",
    "invoice_credits": "0.00",
    "invoice_discount": "0.00",
    "currency": "eur"
  },
  "rates": 5
}
```

***

## Error Handling Best Practices

Throughout this flow, implement proper error handling:

```javascript Example Error Handling theme={null}
const handleApiCall = async (apiCall) => {
  try {
    const response = await apiCall();
    
    if (!response.ok) {
      const error = await response.json();
      
      switch (response.status) {
        case 402:
          // User has outstanding debt
          console.error('Payment required:', error.debt_details);
          break;
        case 403:
          console.error('Authentication failed');
          break;
        case 404:
          console.error('Resource not found');
          break;
        default:
          console.error('API error:', error);
      }
      return null;
    }
    
    return await response.json();
  } catch (error) {
    console.error('Network error:', error);
    return null;
  }
};
```

## Summary

This complete flow demonstrates how to:

1. ✅ **Create user accounts** with proper authentication
2. ✅ **Securely collect payment methods** via Stripe integration
3. ✅ **Discover charging stations** with location-based search
4. ✅ **Initiate charging sessions** with payment authorization
5. ✅ **Monitor session progress** with real-time status updates
6. ✅ **Complete sessions** and generate detailed receipts

The entire process is designed around the backend-to-backend authentication model, where your backend manages users on behalf of your customers while maintaining full control over the user experience.
