Skill: rersozlu/food402 (version 1.0.0)

--- name: food402 description: Order food from TGO Yemek (Trendyol GO), Turkey's leading food delivery service. Use when user wants to order food delivery in Turkey, browse restaurants, search for foods, manage delivery addresses, check order history, or checkout with 3D Secure payment. metadata: {"openclaw": {"emoji": "🍕", "requires": {"bins": ["curl", "jq", "openssl"], "env": ["TGO_EMAIL", "TGO_PASSWORD", "GOOGLE_PLACES_API_KEY"]}, "primaryEnv": "TGO_EMAIL"}} --- # Food402 - TGO Yemek Food Delivery Order food from Trendyol GO (TGO Yemek), Turkey's leading food delivery service. This skill enables complete food ordering: browse restaurants, view menus, customize items, manage cart, and checkout with 3D Secure payment. ## Setup ### OpenClaw Add the following to your `~/.openclaw/openclaw.json`: ```json { "skills": { "entries": { "food402": { "enabled": true, "env": { "TGO_EMAIL": "[REDACTED_SECRET]", "TGO_PASSWORD": "your-tgo-password", "GOOGLE_PLACES_API_KEY": "your-google-api-key" } } } } } ``` ### Claude Code / Cursor / Codex / Gemini CLI Set environment variables in your shell profile (`~/.bashrc`, `~/.zshrc`, etc.): ```bash export TGO_EMAIL="[REDACTED_SECRET]" export TGO_PASSWORD="your-tgo-password" export GOOGLE_PLACES_API_KEY="your-google-api-key" # Optional: for Google Reviews ``` Then reload your shell or run `source ~/.zshrc` (or equivalent). ## Authentication The skill automatically handles authentication. When making API calls: 1. Run `{baseDir}/scripts/auth.sh get-token` to get a valid JWT 2. The script caches tokens in `/tmp/food402-token` with automatic refresh (60s buffer before expiry) 3. If any API call returns 401, clear the token with `{baseDir}/scripts/auth.sh clear-token` and retry **Manual authentication check:** ```bash {baseDir}/scripts/auth.sh check-token ``` ## Required Workflow **IMPORTANT:** You MUST follow this order: 1. **select_address** - REQUIRED first step (sets delivery location for cart) 2. **get_restaurants** or **search_restaurants** - Browse/search restaurants 3. **get_restaurant_menu** - View a restaurant's menu 4. **get_product_details** - Check customization options (if needed) 5. **add_to_basket** - Add items to cart 6. **checkout_ready** - Verify cart is ready for payment 7. **place_order** - Complete the order with 3D Secure If `add_to_basket` fails, try `clear_basket` first then retry. --- ## Address Management Operations ### get_addresses Get user's saved delivery addresses. Call this first to show available addresses. ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response fields:** `id`, `addressName`, `addressLine`, `neighborhoodName`, `districtName`, `cityName`, `latitude`, `longitude` ### select_address **MUST be called before browsing restaurants or adding to basket.** Sets the shipping address for the cart. **Parameters:** - `addressId` (required): Address ID from get_addresses ```bash [REDACTED_SECRET] get-token) curl -s -X POST "https://api.tgoapis.com/web-checkout-apicheckout-santral/shipping" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{"shippingAddressId": {addressId}, "invoiceAddressId": {addressId}}' ``` ### add_address Add a new delivery address. Use get_cities → get_districts → get_neighborhoods to find location IDs first. **Parameters:** - `name` (required): First name - `surname` (required): Last name - `phone` (required): Phone without country code (e.g., "5356437070") - `addressName` (required): Label (e.g., "Home", "Work") - `addressLine` (required): Street address - `cityId` (required): From get_cities - `districtId` (required): From get_districts - `neighborhoodId` (required): From get_neighborhoods - `latitude` (required): Coordinate string - `longitude` (required): Coordinate string - `apartmentNumber`, `floor`, `doorNumber`, `addressDescription` (optional) - `elevatorAvailable` (optional): boolean ```bash [REDACTED_SECRET] get-token) curl -s -X POST "https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{ "name": "{name}", "surname": "{surname}", "phone": "{phone}", "addressName": "{addressName}", "addressLine": "{addressLine}", "cityId": {cityId}, "districtId": {districtId}, "neighborhoodId": {neighborhoodId}, "latitude": "{latitude}", "longitude": "{longitude}", "countryCode": "TR", "elevatorAvailable": false }' | jq ``` **Note:** If response is 429, OTP verification is required. Direct user to add the address at tgoyemek.com instead. ### get_cities Get list of all cities for address selection. ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-user-apimemberaddress-santral/cities" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq '.cities[] | {id, name}' ``` ### get_districts Get districts for a city. **Parameters:** - `cityId` (required): City ID from get_cities ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-user-apimemberaddress-santral/cities/{cityId}/districts" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq '.districts[] | {id, name}' ``` ### get_neighborhoods Get neighborhoods for a district. **Parameters:** - `districtId` (required): District ID from get_districts ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-user-apimemberaddress-santral/districts/{districtId}/neighborhoods" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq '.neighborhoods[] | {id, name}' ``` --- ## Restaurant Discovery Operations ### get_restaurants List restaurants near the selected address. **Requires select_address first.** **Parameters:** - `latitude` (required): From selected address - `longitude` (required): From selected address - `page` (optional): Page number, default 1 - `sortBy` (optional): `RECOMMENDED` (default), `RESTAURANT_SCORE`, or `RESTAURANT_DISTANCE` - `minBasketPrice` (optional): Pass 400 to filter min order >= 400 TL **Sorting keywords (Turkish & English):** - "önerilen" / "recommended" / "popüler" → `RECOMMENDED` - "en yakın" / "closest" / "yakınımdaki" → `RESTAURANT_DISTANCE` - "en iyi" / "best rated" / "en yüksek puanlı" → `RESTAURANT_SCORE` - "en ucuz" / "cheapest" → Use **search_restaurants** instead (returns product prices) ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-discovery-apidiscovery-santral/restaurants/filters?openRestaurants=true&latitude={latitude}&longitude={longitude}&pageSize=50&page={page}" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` Add `&sortType=RESTAURANT_SCORE` or `&sortType=RESTAURANT_DISTANCE` for sorting (omit for RECOMMENDED). **Response fields:** `id`, `name`, `kitchen`, `rating`, `ratingText`, `minBasketPrice`, `averageDeliveryInterval`, `distance`, `neighborhoodName`, `isClosed`, `campaignText` ### search_restaurants Search restaurants and products by keyword. Results include product prices (useful for "cheapest" queries). **IMPORTANT:** Always check `isClosed` field. Never suggest closed restaurants. **Parameters:** - `searchQuery` (required): Search keyword (e.g., "pizza", "burger", "dürüm") - `latitude` (required): From selected address - `longitude` (required): From selected address - `page` (optional): Page number, default 1 ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-restaurant-apirestaurant-santral/restaurants/in/search?searchQuery={searchQuery}&latitude={latitude}&longitude={longitude}&pageSize=50&page={page}" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response includes:** Restaurant info plus `products[]` array with `id`, `name`, `description`, `price` --- ## Menu & Product Operations ### get_restaurant_menu Get a restaurant's full menu with categories and items. **Parameters:** - `restaurantId` (required): Restaurant ID - `latitude` (required): Coordinate - `longitude` (required): Coordinate ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-restaurant-apirestaurant-santral/restaurants/{restaurantId}?latitude={latitude}&longitude={longitude}" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response structure:** - `info`: Restaurant details (id, name, rating, workingHours, deliveryTime, minOrderPrice) - `categories[]`: Menu sections with `items[]` (id, name, description, price, likePercentage) ### get_product_details Get product customization options (ingredients to exclude, modifier groups for extras/sizes). **Parameters:** - `restaurantId` (required): Restaurant ID - `productId` (required): Product ID from menu - `latitude` (required): Coordinate - `longitude` (required): Coordinate ```bash [REDACTED_SECRET] get-token) curl -s -X POST "https://api.tgoapis.com/web-restaurant-apirestaurant-santral/restaurants/{restaurantId}/products/{productId}?latitude={latitude}&longitude={longitude}" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{}' | jq ``` **Response includes `components[]`:** - `type`: `INGREDIENTS` (items to exclude) or `MODIFIER_GROUP` (extras/sizes to select) - `modifierGroupId`: Use this ID when adding modifiers to basket - `options[]`: Available choices with `id`, `name`, `price`, `isPopular` - `isSingleChoice`, `minSelections`, `maxSelections`: Selection rules ### get_product_recommendations Get "goes well with" suggestions for products. **Parameters:** - `restaurantId` (required): Restaurant ID - `productIds` (required): Array of product IDs ```bash [REDACTED_SECRET] get-token) curl -s -X POST "https://api.tgoapis.com/web-discovery-apidiscovery-santral/recommendation/product" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{ "restaurantId": "{restaurantId}", "productIds": ["{productId1}", "{productId2}"], "page": "PDP" }' | jq ``` --- ## Cart Management Operations ### add_to_basket Add items to the shopping cart. **Requires select_address first.** **Parameters:** - `storeId` (required): Restaurant ID (NUMBER) - `latitude` (required): Coordinate (NUMBER, not string) - `longitude` (required): Coordinate (NUMBER, not string) - `items[]` (required): Array of items to add **Item structure:** ```json { "productId": 12345, "quantity": 1, "modifierProducts": [ { "productId": 111, "modifierGroupId": 222, "modifierProducts": [], "ingredientOptions": {"excludes": [], "includes": []} } ], "ingredientOptions": { "excludes": [{"id": 333}], "includes": [] } } ``` ```bash [REDACTED_SECRET] get-token) curl -s -X POST "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts/items" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{ "storeId": {storeId}, "items": [{items}], "latitude": {latitude}, "longitude": {longitude}, "isFlashSale": false, "storePickup": false }' | jq ``` **If this fails,** try `clear_basket` first then retry. ### get_basket Get current cart contents. ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response includes:** `storeGroups[]` with store info and products, `summary[]`, `totalPrice`, `deliveryPrice`, `isEmpty` ### remove_from_basket Remove an item from the cart. **Parameters:** - `itemId` (required): Item UUID from get_basket response (the `itemId` field, NOT `productId`) ```bash [REDACTED_SECRET] get-token) curl -s -X DELETE "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts/items/{itemId}" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` ### clear_basket Clear the entire cart. ```bash [REDACTED_SECRET] get-token) curl -s -X DELETE "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" ``` --- ## Checkout & Payment Operations ### get_saved_cards Get user's saved payment cards (masked). If no cards, user must add one at tgoyemek.com. **Uses Payment API with different headers:** ```bash [REDACTED_SECRET] get-token) curl -s "https://payment.tgoapps.com/v2/cards/" \ -H "Authorization: bearer $TOKEN" \ -H "app-name: TrendyolGo" \ -H "x-applicationid: 1" \ -H "x-channelid: 4" \ -H "x-storefrontid: 1" | jq ``` **Response:** `cards[]` with `cardId`, `maskedCardNumber`, `bankName`, `cardNetwork`, `isDebitCard` ### checkout_ready Verify cart is ready for checkout. Call this before place_order. ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts?cartContext=payment&limitPromoMbs=false" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Check response:** - If `totalProductCount` is 0, cart is empty - Check `warnings[]` for issues (e.g., below minimum order) - Returns full cart details and `totalPrice` ### set_order_note Set order note and service preferences. Call before place_order. **Parameters:** - `note` (optional): Note for courier/restaurant - `noServiceWare` (optional): Don't include plastic/cutlery (default: false) - `contactlessDelivery` (optional): Leave at door (default: false) - `dontRingBell` (optional): Don't ring doorbell (default: false) ```bash [REDACTED_SECRET] get-token) curl -s -X PUT "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts/customerNote" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" \ -d '{ "customerNote": "{note}", "noServiceWare": false, "contactlessDelivery": false, "dontRingBell": false }' ``` ### place_order Place the order with 3D Secure payment. This is a 3-step process. **Parameters:** - `cardId` (required): Card ID from get_saved_cards **Step 1: Get cart with payment context** ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-checkout-apicheckout-santral/carts?cartContext=payment&limitPromoMbs=false" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" ``` **Step 2: Select payment method (Payment API)** ```bash # Get bin code from card's maskedCardNumber (first 6 digits + **) BINCODE="${maskedCardNumber:0:6}**" curl -s -X POST "https://payment.tgoapps.com/v3/payment/options" \ -H "Authorization: bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "app-name: TrendyolGo" \ -H "x-applicationid: 1" \ -H "x-channelid: 4" \ -H "x-storefrontid: 1" \ -d '{ "paymentType": "payWithCard", "data": { "savedCardId": {cardId}, "binCode": "{binCode}", "installmentId": 0, "reward": null, "installmentPostponingSelected": false } }' ``` **Step 3: Submit payment (Payment API)** ```bash curl -s -X POST "https://payment.tgoapps.com/v2/payment/pay" \ -H "Authorization: bearer $TOKEN" \ -H "Content-Type: application/json" \ -H "app-name: TrendyolGo" \ -H "x-applicationid: 1" \ -H "x-channelid: 4" \ -H "x-storefrontid: 1" \ -d '{ "customerSelectedThreeD": false, "paymentOptions": [{"name": "payWithCard", "cardNo": "", "customerSelectedThreeD": false}], "callbackUrl": "https://tgoyemek.com/odeme" }' ``` **3D Secure handling:** If response contains `json.content` (HTML) or `redirectUrl`: 1. Save HTML to temp file 2. Open in browser: `{baseDir}/scripts/3dsecure.sh "$HTML_CONTENT"` 3. Inform user to complete verification in browser --- ## Order History Operations ### get_orders Get user's order history with status. **Parameters:** - `page` (optional): Page number, default 1 ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-checkout-apicheckout-santral/orders?page={page}&pageSize=50" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response:** `orders[]` with `id`, `orderDate`, `store`, `status`, `price`, `products[]` ### get_order_detail Get detailed information about a specific order including delivery status. **Parameters:** - `orderId` (required): Order ID from get_orders ```bash [REDACTED_SECRET] get-token) curl -s "https://api.tgoapis.com/web-checkout-apicheckout-santral/orders/detail?orderId={orderId}" \ -H "Authorization: Bearer $TOKEN" \ -H "x-correlationid: $(uuidgen)" \ -H "pid: $(uuidgen)" \ -H "sid: $(uuidgen)" | jq ``` **Response includes:** Order details, delivery status steps, ETA, products with prices, delivery address --- ## Google Reviews (Optional) ### get_google_reviews Fetch Google Maps rating and reviews for a restaurant. **Requires GOOGLE_PLACES_API_KEY env var.** **Parameters:** - `restaurantId`, `restaurantName`, `neighborhoodName`, `tgoDistance`, `tgoRating`, `latitude`, `longitude` This operation uses Google Places API to find the restaurant and compare ratings. Only use if GOOGLE_PLACES_API_KEY is configured. --- ## Error Handling | Status | Action | |--------|--------| | **401 Unauthorized** | Token expired. Run `{baseDir}/scripts/auth.sh clear-token` then retry the operation. | | **400 Bad Request** | Check parameters. Parse and show the error message from response body. | | **429 Rate Limited** | OTP verification required. Direct user to complete the action at tgoyemek.com instead. | | **5xx Server Error** | TGO service temporarily unavailable. Wait a moment and retry once. | | **3D Secure** | Save HTML content, open browser with `{baseDir}/scripts/3dsecure.sh`, inform user to complete verification. | Always parse error responses and present the error message clearly to the user. --- ## Guidelines - **Always authenticate** before making API calls. Use the auth.sh helper. - **Never expose** raw credentials, JWTs, or tokens to the user. - **Confirm destructive operations** (clear_basket, place_order) with the user before executing. - **Check `isClosed`** before suggesting restaurants from search results. - **Present results** in a clean, readable format rather than raw JSON dumps. - **Follow the required workflow**: select_address → browse → menu → add to basket → checkout. - **Handle coordinates correctly**: get_restaurants uses STRING coordinates, add_to_basket uses NUMBER coordinates. - **If add_to_basket fails**, try clear_basket first then retry. - **For payment**, always use the Payment API headers (lowercase "bearer", app-name, x-applicationid, etc.).

path: scripts/api.sh
content: #!/usr/bin/env bash
# scripts/api.sh - TGO Yemek API Wrapper
# Usage: {baseDir}/scripts/api.sh <method> <endpoint> [data]
# Methods: get, post, put, delete, payment-get, payment-post

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API_BASE="https://api.tgoapis.com"
PAYMENT_API_BASE="https://payment.tgoapps.com"
USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"

# Generate UUID
generate_uuid() {
  if command -v uuidgen &>/dev/null; then
    uuidgen | tr '[:upper:]' '[:lower:]'
  else
    # Fallback using /dev/urandom
    cat /proc/sys/kernel/random/uuid 2>/dev/null || \
    od -x /dev/urandom | head -1 | awk '{OFS="-"; print $2$3,$4,$5,$6,$7$8$9}'
  fi
}

# Get auth token
get_token() {
  "$SCRIPT_DIR/auth.sh" get-token
}

# Create main API headers
create_headers() {
  local token="$1"
  local content_type="${2:-}"

  local headers=(
    -H "Accept: application/json, text/plain, */*"
    -H "Authorization: Bearer $token"
    -H "User-Agent: $USER_AGENT"
    -H "Origin: https://tgoyemek.com"
    -H "x-correlationid: $(generate_uuid)"
    -H "pid: $(generate_uuid)"
    -H "sid: $(generate_uuid)"
  )

  if [ -n "$content_type" ]; then
    headers+=(-H "Content-Type: $content_type")
  fi

  printf '%s\n' "${headers[@]}"
}

# Create payment API headers
create_payment_headers() {
  local token="$1"

  cat <<EOF
-H
accept: */*
-H
accept-language: tr-TR
-H
Authorization: bearer $token
-H
Content-Type: application/json
-H
User-Agent: $USER_AGENT
-H
referer: https://payment.tgoapps.com/v3/tgo/card-fragment?application-id=1&storefront-id=1&culture=tr-TR
-H
app-name: TrendyolGo
-H
x-applicationid: 1
-H
x-channelid: 4
-H
x-storefrontid: 1
-H
x-features: OPTIONAL_REBATE;MEAL_CART_ENABLED;MEAL_CARD_TRENDYOL_PROMOTION;PICKUP_FEE_ENABLED;VAS_QUANTITY_ENABLED;
-H
x-supported-payment-options: MULTINET;SODEXO;EDENRED;ON_DELIVERY;SETCARD
-H
x-session-id:
-H
x-personalization-id:
EOF
}

# Make API request with retry on 401
api_request() {
  local method="$1"
  local url="$2"
  local data="${3:-}"
  local is_payment="${4:-false}"
  local retry_count=0
  local max_retries=1

  while [ $retry_count -le $max_retries ]; do
    local token
    [REDACTED_SECRET])

    local headers_array=()
    if [ "$is_payment" = "true" ]; then
      while IFS= read -r line; do
        headers_array+=("$line")
      done < <(create_payment_headers "$token")
    else
      while IFS= read -r line; do
        headers_array+=("$line")
      done < <(create_headers "$token" "application/json")
    fi

    local response
    local http_code

    if [ -n "$data" ]; then
      response=$(curl -s -w "\n%{http_code}" -X "$method" "$url" \
        "${headers_array[@]}" \
        -d "$data" 2>/dev/null)
    else
      response=$(curl -s -w "\n%{http_code}" -X "$method" "$url" \
        "${headers_array[@]}" 2>/dev/null)
    fi

    http_code=$(echo "$response" | tail -1)
    response=$(echo "$response" | sed '$d')

    # Handle 401 - re-authenticate and retry
    if [ "$http_code" = "401" ] && [ $retry_count -lt $max_retries ]; then
      "$SCRIPT_DIR/auth.sh" clear-token >/dev/null
      retry_count=$((retry_count + 1))
      continue
    fi

    # Return response with status info
    if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
      echo "$response"
    else
      echo "{\"error\": \"HTTP $http_code\", \"response\": $response}" >&2
      exit 1
    fi
    return
  done
}

# Main command dispatcher
case "${1:-}" in
  get)
    api_request "GET" "${API_BASE}${2}"
    ;;
  post)
    api_request "POST" "${API_BASE}${2}" "${3:-}"
    ;;
  put)
    api_request "PUT" "${API_BASE}${2}" "${3:-}"
    ;;
  delete)
    api_request "DELETE" "${API_BASE}${2}"
    ;;
  payment-get)
    api_request "GET" "${PAYMENT_API_BASE}${2}" "" "true"
    ;;
  payment-post)
    api_request "POST" "${PAYMENT_API_BASE}${2}" "${3:-}" "true"
    ;;
  *)
    echo "Usage: $0 {get|post|put|delete|payment-get|payment-post} <endpoint> [data]" >&2
    echo "Examples:" >&2
    echo "  $0 get /web-user-apimemberaddress-santral/addresses" >&2
    echo "  $0 post /web-checkout-apicheckout-santral/shipping '{\"shippingAddressId\":123}'" >&2
    exit 1
    ;;
esac


path: scripts/auth.sh
content: #!/usr/bin/env bash
# scripts/auth.sh - TGO Yemek Authentication Helper
# Usage: {baseDir}/scripts/auth.sh <command>
# Commands: get-token, login, check-token, clear-token

set -euo pipefail

USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
TOKEN_FILE="/tmp/food402-token"
EXPIRY_FILE="/tmp/food402-token-expiry"

# Check required environment variables
check_credentials() {
  if [ -z "${TGO_EMAIL:-}" ] || [ -z "${TGO_PASSWORD:-}" ]; then
    echo '{"error": "TGO_EMAIL and TGO_PASSWORD environment variables are required"}' >&2
    exit 1
  fi
}

# Decode JWT payload to extract expiry
decode_jwt_expiry() {
  local token="$1"
  # Extract payload (second part), base64 decode, parse exp field
  local payload
  payload=$(echo "$token" | cut -d. -f2)
  # Add padding if needed
  local padding=$((4 - ${#payload} % 4))
  if [ $padding -ne 4 ]; then
    payload="${payload}$(printf '%*s' $padding | tr ' ' '=')"
  fi
  # Decode and extract exp (multiply by 1000 for milliseconds)
  echo "$payload" | base64 -d 2>/dev/null | sed -n 's/.*"exp":\([0-9]*\).*/\1/p' | awk '{print $1 * 1000}'
}

# Perform fresh login
do_login() {
  check_credentials

  # Step 1: Get CSRF token
  local csrf_response
  csrf_response=$(curl -s -c - "https://tgoyemek.com/api/auth/csrf" \
    -H "User-Agent: $USER_AGENT" 2>/dev/null)

  local csrf_token
  csrf_token=$(echo "$csrf_response" | grep -o 'tgo-csrf-token[[:space:]]*[^[:space:]]*' | awk '{print $2}' | head -1)

  if [ -z "$csrf_token" ]; then
    echo '{"error": "Failed to get CSRF token"}' >&2
    exit 1
  fi

  # Step 2: Login with credentials
  local login_response
  login_response=$(curl -s -c - -X POST "https://tgoyemek.com/api/auth/login" \
    -H "Content-Type: text/plain;charset=UTF-8" \
    -H "Cookie: tgo-csrf-[REDACTED_SECRET]" \
    -H "User-Agent: $USER_AGENT" \
    -d "{\"username\":\"$TGO_EMAIL\",\"password\":\"$TGO_PASSWORD\",\"csrfToken\":\"$csrf_token\"}" 2>/dev/null)

  # Step 3: Extract tgo-token from cookies
  local token
  [REDACTED_SECRET] "$login_response" | grep -o 'tgo-token[[:space:]]*[^[:space:]]*' | awk '{print $2}' | head -1)

  if [ -z "$token" ]; then
    echo '{"error": "Login failed - no token received. Check credentials."}' >&2
    exit 1
  fi

  # Cache token and expiry
  echo "$token" > "$TOKEN_FILE"
  local expiry
  expiry=$(decode_jwt_expiry "$token")
  echo "$expiry" > "$EXPIRY_FILE"

  echo "$token"
}

# Check if cached token is still valid (with 60s buffer)
is_token_valid() {
  if [ ! -f "$TOKEN_FILE" ] || [ ! -f "$EXPIRY_FILE" ]; then
    return 1
  fi

  local expiry
  expiry=$(cat "$EXPIRY_FILE" 2>/dev/null || echo "0")
  local now
  now=$(date +%s)
  now=$((now * 1000))

  # Check if token expires within 60 seconds
  local buffer=60000
  if [ "$now" -lt "$((expiry - buffer))" ]; then
    return 0
  fi
  return 1
}

# Get token (cached or fresh)
get_token() {
  if is_token_valid; then
    cat "$TOKEN_FILE"
  else
    do_login
  fi
}

# Clear cached token
clear_token() {
  rm -f "$TOKEN_FILE" "$EXPIRY_FILE"
  echo '{"success": true, "message": "Token cache cleared"}'
}

# Check token status
check_token() {
  if [ ! -f "$TOKEN_FILE" ]; then
    echo '{"valid": false, "reason": "No cached token"}'
    return
  fi

  if is_token_valid; then
    local expiry
    expiry=$(cat "$EXPIRY_FILE")
    local now
    now=$(date +%s)
    now=$((now * 1000))
    local remaining=$((($expiry - $now) / 1000))
    echo "{\"valid\": true, \"expiresIn\": ${remaining}}"
  else
    echo '{"valid": false, "reason": "Token expired"}'
  fi
}

# Main command dispatcher
case "${1:-}" in
  get-token)
    get_token
    ;;
  login)
    do_login
    ;;
  check-token)
    check_token
    ;;
  clear-token)
    clear_token
    ;;
  *)
    echo "Usage: $0 {get-token|login|check-token|clear-token}" >&2
    exit 1
    ;;
esac


path: scripts/3dsecure.sh
content: #!/usr/bin/env bash
# scripts/3dsecure.sh - 3D Secure Browser Handler
# Usage: {baseDir}/scripts/3dsecure.sh <html_content>
# Opens 3D Secure verification page in system browser

set -euo pipefail

HTML_CONTENT="${1:-}"

if [ -z "$HTML_CONTENT" ]; then
  echo '{"error": "HTML content required"}' >&2
  exit 1
fi

# Create temp file
TEMP_FILE="/tmp/food402-3dsecure-$(date +%s).html"
echo "$HTML_CONTENT" > "$TEMP_FILE"

# Open in default browser based on platform
case "$(uname -s)" in
  Darwin)
    open "$TEMP_FILE"
    ;;
  Linux)
    if command -v xdg-open &>/dev/null; then
      xdg-open "$TEMP_FILE"
    elif command -v gnome-open &>/dev/null; then
      gnome-open "$TEMP_FILE"
    else
      echo '{"error": "No browser opener found (xdg-open or gnome-open)"}' >&2
      exit 1
    fi
    ;;
  CYGWIN*|MINGW*|MSYS*)
    start "" "$TEMP_FILE"
    ;;
  *)
    echo '{"error": "Unsupported platform"}' >&2
    exit 1
    ;;
esac

echo "{\"success\": true, \"message\": \"3D Secure page opened in browser\", \"tempFile\": \"$TEMP_FILE\"}"

# Clean up after 5 minutes in background
(sleep 300 && rm -f "$TEMP_FILE") &>/dev/null &


path: references/api-quick-ref.md
content: # TGO Yemek API Quick Reference

## Base URLs
- **Main API:** `https://api.tgoapis.com`
- **Payment API:** `https://payment.tgoapps.com`

## Authentication
- Login: `POST https://tgoyemek.com/api/auth/login`
- CSRF first: `GET https://tgoyemek.com/api/auth/csrf`
- Token cookie: `tgo-token`

## Main API Headers
```
Authorization: Bearer {token}
x-correlationid: {uuid}
pid: {uuid}
sid: {uuid}
```

## Payment API Headers
```
Authorization: bearer {token}  # lowercase 'bearer'
app-name: TrendyolGo
x-applicationid: 1
x-channelid: 4
x-storefrontid: 1
```

## Endpoints Reference

### Address Management
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/web-user-apimemberaddress-santral/addresses` | GET | List addresses |
| `/web-user-apimemberaddress-santral/addresses` | POST | Add address |
| `/web-user-apimemberaddress-santral/cities` | GET | List cities |
| `/web-user-apimemberaddress-santral/cities/{id}/districts` | GET | List districts |
| `/web-user-apimemberaddress-santral/districts/{id}/neighborhoods` | GET | List neighborhoods |

### Cart
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/web-checkout-apicheckout-santral/shipping` | POST | Set address |
| `/web-checkout-apicheckout-santral/carts` | GET | Get cart |
| `/web-checkout-apicheckout-santral/carts` | DELETE | Clear cart |
| `/web-checkout-apicheckout-santral/carts/items` | POST | Add items |
| `/web-checkout-apicheckout-santral/carts/items/{id}` | DELETE | Remove item |
| `/web-checkout-apicheckout-santral/carts/customerNote` | PUT | Set note |
| `/web-checkout-apicheckout-santral/carts?cartContext=payment` | GET | Checkout ready |

### Restaurants
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/web-discovery-apidiscovery-santral/restaurants/filters` | GET | List restaurants |
| `/web-restaurant-apirestaurant-santral/restaurants/in/search` | GET | Search |
| `/web-restaurant-apirestaurant-santral/restaurants/{id}` | GET | Get menu |
| `/web-restaurant-apirestaurant-santral/restaurants/{id}/products/{pid}` | POST | Product details |
| `/web-discovery-apidiscovery-santral/recommendation/product` | POST | Recommendations |

### Orders
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/web-checkout-apicheckout-santral/orders` | GET | Order history |
| `/web-checkout-apicheckout-santral/orders/detail` | GET | Order detail |

### Payment (payment.tgoapps.com)
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v2/cards/` | GET | Saved cards |
| `/v3/payment/options` | POST | Select payment |
| `/v2/payment/pay` | POST | Place order |

## Common Query Parameters

### get_restaurants
- `openRestaurants=true`
- `latitude`, `longitude` (required)
- `pageSize=50`, `page=1`
- `sortType`: RESTAURANT_SCORE, RESTAURANT_DISTANCE (omit for RECOMMENDED)
- `minBasketPrice=400` (optional filter)

### search_restaurants
- `searchQuery` (required)
- `latitude`, `longitude` (required)
- `pageSize=50`, `page=1`

## add_to_basket Body Structure
```json
{
  "storeId": 12345,
  "items": [{
    "productId": 67890,
    "quantity": 1,
    "modifierProducts": [{
      "productId": 111,
      "modifierGroupId": 222,
      "modifierProducts": [],
      "ingredientOptions": {"excludes": [], "includes": []}
    }],
    "ingredientOptions": {
      "excludes": [{"id": 333}],
      "includes": []
    }
  }],
  "latitude": 41.0082,
  "longitude": 28.9784,
  "isFlashSale": false,
  "storePickup": false
}
```
**Note:** latitude/longitude are NUMBERS here, not strings.

## place_order Flow
1. GET `/carts?cartContext=payment` (Main API)
2. POST `/v3/payment/options` (Payment API)
3. POST `/v2/payment/pay` (Payment API)

If response has `json.content` or `htmlContent` → 3D Secure required → open in browser.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (HIGH)