# Checkout API Documentation

## Overview

The Checkout API provides endpoints for saving billing and shipping information during the checkout process. This is a simple, streamlined API that validates and persists checkout data to prepare for payment processing.

**Key Features:**
- Validates all billing and shipping address information
- Saves checkout data in JSON format
- Returns next step directive for payment flow
- Supports both guest and authenticated customers
- Comprehensive validation rules

## Base URL

```
https://adminv2.missio.io/api/catalog
```

## Authentication

**Required Header:**
- `X-Company-Hash`: Company identifier (required for all requests)

**Optional Header:**
- `Authorization: Bearer {token}`: For authenticated customer checkouts (links data to customer account)

**Cart Token:**
- Use `cart_token` query parameter to identify the cart
- Obtained from previous Cart API responses
- Pass as: `POST /checkout?cart_token=abc123`

---

## Endpoint

### Save Checkout Form

Save billing and shipping information to the order cart.

**Endpoint:** `POST /checkout`

**Headers:**
```
X-Company-Hash: your-company-hash
Authorization: Bearer {token}  (optional - for authenticated customers)
Content-Type: application/json
```

**Query Parameters:**
```
cart_token: abc123  (required - from cart response)
```

**Request Body:**
```json
{
  "_token": "xxOsb97nIMwq3D5KmQiqyHFqPfBlENTPZSAN6Xts",
  "PhysicalProductinList": "1",
  "billing_first_name": "John",
  "billing_last_name": "Doe66",
  "billing_email": "john.doe@example.com",
  "billing_company_name": "",
  "billing_address": "123 Main Street",
  "billing_address2": "",
  "billing_city": "Boston",
  "billing_country": "US",
  "billing_state": "Arkansas",
  "billing_zip": "02101",
  "billing_phone": "(123) 456-7890",
  "shipping_first_name": "John",
  "shipping_last_name": "Doe66",
  "shipping_email": "john.doe@example.com",
  "shipping_company_name": "",
  "shipping_address": "123 Main Street",
  "shipping_address2": "",
  "shipping_city": "Boston",
  "shipping_country": "US",
  "shipping_state": "Arkansas",
  "shipping_zip": "02101",
  "shipping_phone": "(123) 456-7890"
}
```

**Request Fields:**

**Billing Address (required):**
- `billing_first_name`: First name
- `billing_last_name`: Last name
- `billing_email`: Email address
- `billing_address`: Street address
- `billing_address2`: Address line 2 (optional)
- `billing_city`: City
- `billing_state`: State/Province
- `billing_zip`: ZIP/Postal code
- `billing_country`: Country code
- `billing_phone`: Phone number
- `billing_company_name`: Company name (optional)

**Shipping Address (required):**
- `shipping_first_name`: First name
- `shipping_last_name`: Last name
- `shipping_email`: Email address
- `shipping_address`: Street address
- `shipping_address2`: Address line 2 (optional)
- `shipping_city`: City
- `shipping_state`: State/Province
- `shipping_zip`: ZIP/Postal code
- `shipping_country`: Country code
- `shipping_phone`: Phone number
- `shipping_company_name`: Company name (optional)

**Additional Fields:**
- `_token`: CSRF token (from form)
- `PhysicalProductinList`: "1" if physical products, "0" if digital only

**Example Request:**
```bash
curl -X POST "https://adminv2.missio.io/api/catalog/checkout?cart_token=5f8a9b7c6d5e4f3g2h1i" \
  -H "X-Company-Hash: your-company-hash" \
  -H "Content-Type: application/json" \
  -d '{
    "billing_first_name": "John",
    "billing_last_name": "Doe66",
    "billing_email": "john.doe@example.com",
    "billing_address": "123 Main Street",
    "billing_city": "Boston",
    "billing_state": "Arkansas",
    "billing_zip": "02101",
    "billing_country": "US",
    "billing_phone": "(123) 456-7890",
    "shipping_first_name": "John",
    "shipping_last_name": "Doe66",
    "shipping_email": "john.doe@example.com",
    "shipping_address": "123 Main Street",
    "shipping_city": "Boston",
    "shipping_state": "Arkansas",
    "shipping_zip": "02101",
    "shipping_country": "US",
    "shipping_phone": "(123) 456-7890",
    "PhysicalProductinList": "1"
  }'
```

**Response (200 OK):**
```json
{
  "status": "success",
  "message": "Checkout data saved successfully",
  "data": {
    "cart_token": "5f8a9b7c6d5e4f3g2h1i",
    "next_step": "payment"
  }
}
```

**Response Fields:**
- `status`: "success" if data saved
- `message`: Confirmation message
- `data.cart_token`: Cart token (use for payment)
- `data.next_step`: "payment" (directive for next page)

---

## Validation Rules

### Required Fields

All billing and shipping fields are **required**:

**Billing:**
- `billing_first_name` - Max 255 characters
- `billing_last_name` - Max 255 characters
- `billing_email` - Valid email format
- `billing_address` - Max 255 characters
- `billing_city` - Max 255 characters
- `billing_state` - Max 255 characters
- `billing_zip` - Max 20 characters
- `billing_country` - Max 100 characters
- `billing_phone` - Max 20 characters

**Shipping:**
- `shipping_first_name` - Max 255 characters
- `shipping_last_name` - Max 255 characters
- `shipping_email` - Valid email format
- `shipping_address` - Max 255 characters
- `shipping_city` - Max 255 characters
- `shipping_state` - Max 255 characters
- `shipping_zip` - Max 20 characters
- `shipping_country` - Max 100 characters
- `shipping_phone` - Max 20 characters

### Optional Fields

- `billing_company_name` - Max 255 characters
- `billing_address2` - Max 255 characters
- `shipping_company_name` - Max 255 characters
- `shipping_address2` - Max 255 characters
- `_token` - CSRF token
- `PhysicalProductinList` - "0" or "1"

---

## Error Handling

### HTTP Status Codes

- `200 OK`: Successfully saved checkout data
- `400 Bad Request`: Cart is empty or invalid request
- `404 Not Found`: Cart not found or invalid company
- `422 Unprocessable Entity`: Validation errors

### Error Response Format

```json
{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "billing_first_name": ["The billing first name field is required."],
    "billing_email": ["The billing email must be a valid email address."]
  }
}
```

### Common Error Scenarios

| Scenario | Status | Message |
|----------|--------|---------|
| Missing X-Company-Hash | 404 | Invalid company identifier |
| Invalid cart_token | 404 | Cart not found |
| No items in cart | 400 | Cart is empty |
| Missing required field | 422 | Validation failed + field errors |
| Invalid email format | 422 | Validation failed + email error |

---

## Workflow

### Complete Checkout Flow

```
1. User adds items to cart
   GET /cart
   → Returns: cart_token, items, totals

2. User navigates to checkout
   POST /checkout?cart_token=abc123
   {
     billing_first_name: "John",
     billing_last_name: "Doe",
     billing_email: "john@example.com",
     ...all other fields...
   }
   → Returns: next_step: "payment"

3. User proceeds to payment
   POST /payment?cart_token=abc123
   {
     payment_method: "stripe",
     ...payment details...
   }
   → Returns: order confirmation
```

---

## Data Storage

### Database Column

Checkout data is saved to the `order_carts` table in the `checkoutData` column as JSON:

```sql
UPDATE order_carts 
SET checkoutData = JSON_OBJECT(
  '_token', 'xxOsb97nIMwq3D5KmQiqyHFqPfBlENTPZSAN6Xts',
  'PhysicalProductinList', '1',
  'billing_first_name', 'John',
  'billing_last_name', 'Doe66',
  'billing_email', 'john.doe@example.com',
  'billing_address', '123 Main Street',
  ...
)
WHERE cart_id = '5f8a9b7c6d5e4f3g2h1i';
```

### JSON Structure

The stored JSON includes all submitted fields as-is:
- All billing address fields
- All shipping address fields
- Metadata (_token, PhysicalProductinList)
- Any additional form fields

---

## Implementation Notes

### Guest vs. Authenticated

**Guest Checkout:**
- Use `cart_token` from cart response
- No Authorization header required
- Data linked to cart via `cart_id`

**Authenticated Checkout:**
- Include `Authorization: Bearer {token}` header
- Include `cart_token` query parameter
- Data linked to both customer and cart

### Validation Timing

- Validates all fields before saving
- Returns validation errors if any field invalid
- Does NOT save partially validated data
- All-or-nothing approach ensures data integrity

### Next Step

- Always returns `next_step: "payment"` on success
- Use this directive to navigate to payment page
- Payment API will use same `cart_token`

---

## Related Documentation

- [Cart API](CART_API.md) - Shopping cart management
- [Catalog API](CATALOG_API.md) - Product browsing
- [API Documentation](API_DOCUMENTATION.md) - Authentication

---

## Changelog

### Version 1.0 (Current)

**Features:**
- ✅ Save billing address information
- ✅ Save shipping address information
- ✅ Full validation of all required fields
- ✅ JSON data persistence
- ✅ Guest and authenticated support
- ✅ Cart verification before saving
- ✅ Clear error messages

---

## Support

For questions or issues:
- Check existing documentation: [API_DOCUMENTATION.md](API_DOCUMENTATION.md)
- Review Postman collection for examples
- Contact development team
