# Send conversations from any language

Send each conversation to Cortad over HTTPS after every reply, signed with your key, from Go, Ruby, PHP, Java, C#, Rust, curl or an edge function.

Send your app's conversations to Cortad with one HTTPS request after each reply. This is how an app in Go, Java, C#, Ruby, PHP, Rust or any other language without an SDK connects, and your coding agent writes it into your app during setup. It also fits an app on an edge runtime, or one that answers people through a relay such as a WhatsApp, Slack or voice webhook. A Node or Python app can use [the Node SDK](https://cortad.com/docs/production-node.md) or [the Python SDK](https://cortad.com/docs/production-python.md) instead.

## Get your key

Your key, `CORTAD_INGEST_KEY`, comes from the same setup as the SDKs: see [Get your key](https://cortad.com/docs/production-node.md#get-your-key). It starts with `ct_ing_`. Every request is signed with it, so keep it on your server: never in a browser, and never inside a mobile app.

## Send after each reply

After each reply your app sends, POST the whole conversation so far, oldest message first, to `https://cortad.com/api/v1/conversations`. A copy with as many messages as one you already sent adds nothing, so a retry is safe. A copy with more adds its newest reply.

Each conversation sent here is shown on **Conversations** as a real person's, so send from production only.

## The body

```json
{
  "id": "conv_8f2c",
  "user": "20668f17abcff6a999719c346b4fa97b4071069522ceac09fef6978accadbaf2",
  "country": "SA",
  "channel": "whatsapp",
  "messages": [
    { "role": "user", "text": "Where is my order?", "at": "2026-11-08T14:02:11Z" },
    { "role": "assistant", "text": "It ships Monday.", "at": "2026-11-08T14:02:13Z" }
  ]
}
```

| Field | What it is |
| --- | --- |
| `id` | Your own id for the conversation, 1 to 200 characters. Send the same id every time. |
| `user` | Optional. The person, as the SHA-256 of `<your key>:user:<your user id>` in lowercase hex. The SDKs hash a user the same way, so a person sent both ways is one person. |
| `country` | Optional. Where the person is, as a two-letter ISO 3166 code in capitals, such as `SA`. |
| `channel` | Optional. How they reached your app: `web`, `whatsapp`, `slack`, `discord`, `telegram`, `voice`, `email`, `sms` or `other`. |
| `messages` | 1 to 200 messages, oldest first. Each has a `role` of `user` or `assistant`, a `text` of 1 to 8,000 characters, and `at`: when it was sent, with its zone. A time later than now is refused. |

Any other field is refused, and a body is at most 1 MiB.

## Sign the request

The key itself never travels. Each request carries its first 15 characters and a signature made with it:

1. Serialize the body once. Those exact bytes are what you hash and what you send.
2. `secret` is the SHA-256 of your whole key, as lowercase hex. That hex text is the HMAC key.
3. `timestamp` is the time now in milliseconds since 1970, as digits. It must be within five minutes of Cortad's clock.
4. `nonce` is 16 random bytes as lowercase hex. Make a new one for every request, a retry included.
5. `signature` is the HMAC-SHA-256 of `v1.<timestamp>.<nonce>.<SHA-256 of the body in lowercase hex>`, keyed with `secret`, as lowercase hex.

Send these headers with the body:

| Header | Value |
| --- | --- |
| `content-type` | `application/json` |
| `x-cortad-key` | The first 15 characters of your key |
| `x-cortad-timestamp` | `timestamp` |
| `x-cortad-nonce` | `nonce` |
| `x-cortad-signature` | `v1=` followed by `signature` |

## What comes back

| Status | What it means |
| --- | --- |
| `202` | Accepted: `{"added": true}`, or `{"added": false}` when a copy with this many messages was already sent. |
| `400` | The body broke a rule above. `error` says which rule and where. |
| `401` | The key id, the timestamp or the signature is wrong. Most often the timestamp is in seconds, or the body was serialized again after it was signed. |
| `409` | This nonce was already used. Sign again with a new one. |
| `413` | The body is over 1 MiB. |
| `429` | Too many requests from your address. Wait the seconds in `Retry-After`, then sign again and send. |

## The same send in each language

Each example sends the conversation above, without `user`, `country` and `channel`, and prints what came back.

### curl and openssl

```bash
KEY="$CORTAD_INGEST_KEY"
BODY='{"id":"conv_8f2c","messages":[{"role":"user","text":"Where is my order?","at":"2026-11-08T14:02:11Z"},{"role":"assistant","text":"It ships Monday.","at":"2026-11-08T14:02:13Z"}]}'
SECRET=$(printf %s "$KEY" | openssl dgst -sha256 -r | cut -d' ' -f1)
TIMESTAMP=$(( $(date +%s) * 1000 ))
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf %s "$BODY" | openssl dgst -sha256 -r | cut -d' ' -f1)
SIGNATURE=$(printf %s "v1.$TIMESTAMP.$NONCE.$BODY_HASH" | openssl dgst -sha256 -hmac "$SECRET" -r | cut -d' ' -f1)

curl -sS https://cortad.com/api/v1/conversations \
  -H 'content-type: application/json' \
  -H "x-cortad-key: ${KEY:0:15}" \
  -H "x-cortad-timestamp: $TIMESTAMP" \
  -H "x-cortad-nonce: $NONCE" \
  -H "x-cortad-signature: v1=$SIGNATURE" \
  --data-binary "$BODY" \
  --write-out ' %{http_code}\n'
```

### Go

```go
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"time"
)

type Message struct {
	Role string `json:"role"`
	Text string `json:"text"`
	At   string `json:"at"`
}

func sha256Hex(b []byte) string {
	sum := sha256.Sum256(b)
	return hex.EncodeToString(sum[:])
}

func main() {
	key := os.Getenv("CORTAD_INGEST_KEY")
	body, err := json.Marshal(map[string]any{
		"id": "conv_8f2c",
		"messages": []Message{
			{Role: "user", Text: "Where is my order?", At: "2026-11-08T14:02:11Z"},
			{Role: "assistant", Text: "It ships Monday.", At: "2026-11-08T14:02:13Z"},
		},
	})
	if err != nil {
		panic(err)
	}
	random := make([]byte, 16)
	if _, err := rand.Read(random); err != nil {
		panic(err)
	}
	nonce := hex.EncodeToString(random)
	timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
	mac := hmac.New(sha256.New, []byte(sha256Hex([]byte(key))))
	mac.Write([]byte("v1." + timestamp + "." + nonce + "." + sha256Hex(body)))

	req, err := http.NewRequest("POST", "https://cortad.com/api/v1/conversations", bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("content-type", "application/json")
	req.Header.Set("x-cortad-key", key[:15])
	req.Header.Set("x-cortad-timestamp", timestamp)
	req.Header.Set("x-cortad-nonce", nonce)
	req.Header.Set("x-cortad-signature", "v1="+hex.EncodeToString(mac.Sum(nil)))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	answer, _ := io.ReadAll(res.Body)
	fmt.Println(res.StatusCode, string(answer))
}
```

### Ruby

```ruby
require "json"
require "net/http"
require "openssl"
require "securerandom"

key = ENV.fetch("CORTAD_INGEST_KEY")
body = JSON.generate(
  id: "conv_8f2c",
  messages: [
    { role: "user", text: "Where is my order?", at: "2026-11-08T14:02:11Z" },
    { role: "assistant", text: "It ships Monday.", at: "2026-11-08T14:02:13Z" }
  ]
)
secret = OpenSSL::Digest::SHA256.hexdigest(key)
timestamp = (Time.now.to_f * 1000).to_i.to_s
nonce = SecureRandom.hex(16)
signature = OpenSSL::HMAC.hexdigest("SHA256", secret, "v1.#{timestamp}.#{nonce}.#{OpenSSL::Digest::SHA256.hexdigest(body)}")

response = Net::HTTP.post(
  URI("https://cortad.com/api/v1/conversations"),
  body,
  "content-type" => "application/json",
  "x-cortad-key" => key[0, 15],
  "x-cortad-timestamp" => timestamp,
  "x-cortad-nonce" => nonce,
  "x-cortad-signature" => "v1=#{signature}"
)
puts "#{response.code} #{response.body}"
```

### PHP

```php
<?php
$key = getenv('CORTAD_INGEST_KEY');
$body = json_encode([
    'id' => 'conv_8f2c',
    'messages' => [
        ['role' => 'user', 'text' => 'Where is my order?', 'at' => '2026-11-08T14:02:11Z'],
        ['role' => 'assistant', 'text' => 'It ships Monday.', 'at' => '2026-11-08T14:02:13Z'],
    ],
]);
$timestamp = (string) (int) (microtime(true) * 1000);
$nonce = bin2hex(random_bytes(16));
$signature = hash_hmac('sha256', "v1.$timestamp.$nonce." . hash('sha256', $body), hash('sha256', $key));

$request = curl_init('https://cortad.com/api/v1/conversations');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'content-type: application/json',
        'x-cortad-key: ' . substr($key, 0, 15),
        "x-cortad-timestamp: $timestamp",
        "x-cortad-nonce: $nonce",
        "x-cortad-signature: v1=$signature",
    ],
]);
$answer = curl_exec($request);
echo curl_getinfo($request, CURLINFO_RESPONSE_CODE), ' ', $answer, "\n";
```

### Java

Java 17 or later. The standard library has no JSON writer, so the body is written out here; in your app, write it with your JSON library.

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SendConversation {
    static String sha256Hex(byte[] bytes) throws Exception {
        return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
    }

    public static void main(String[] args) throws Exception {
        String key = System.getenv("CORTAD_INGEST_KEY");
        byte[] body = """
            {"id":"conv_8f2c","messages":[
              {"role":"user","text":"Where is my order?","at":"2026-11-08T14:02:11Z"},
              {"role":"assistant","text":"It ships Monday.","at":"2026-11-08T14:02:13Z"}]}
            """.getBytes(StandardCharsets.UTF_8);
        String timestamp = Long.toString(System.currentTimeMillis());
        byte[] random = new byte[16];
        new SecureRandom().nextBytes(random);
        String nonce = HexFormat.of().formatHex(random);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(sha256Hex(key.getBytes(StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        String signed = "v1." + timestamp + "." + nonce + "." + sha256Hex(body);
        String signature = HexFormat.of().formatHex(mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)));

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://cortad.com/api/v1/conversations"))
            .header("content-type", "application/json")
            .header("x-cortad-key", key.substring(0, 15))
            .header("x-cortad-timestamp", timestamp)
            .header("x-cortad-nonce", nonce)
            .header("x-cortad-signature", "v1=" + signature)
            .POST(HttpRequest.BodyPublishers.ofByteArray(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

### C#

A .NET 8 console app.

```csharp
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

static string Hex(byte[] bytes) => Convert.ToHexString(bytes).ToLowerInvariant();

var key = Environment.GetEnvironmentVariable("CORTAD_INGEST_KEY")!;
var body = JsonSerializer.SerializeToUtf8Bytes(new
{
    id = "conv_8f2c",
    messages = new[]
    {
        new { role = "user", text = "Where is my order?", at = "2026-11-08T14:02:11Z" },
        new { role = "assistant", text = "It ships Monday.", at = "2026-11-08T14:02:13Z" },
    },
});
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
var nonce = Hex(RandomNumberGenerator.GetBytes(16));
var secret = Hex(SHA256.HashData(Encoding.UTF8.GetBytes(key)));
var signature = Hex(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"v1.{timestamp}.{nonce}.{Hex(SHA256.HashData(body))}")));

using var request = new HttpRequestMessage(HttpMethod.Post, "https://cortad.com/api/v1/conversations") { Content = new ByteArrayContent(body) };
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Add("x-cortad-key", key[..15]);
request.Headers.Add("x-cortad-timestamp", timestamp);
request.Headers.Add("x-cortad-nonce", nonce);
request.Headers.Add("x-cortad-signature", $"v1={signature}");
using var client = new HttpClient();
using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

### Rust

The standard library has no SHA-256 or HTTP client, so this uses these crates in `Cargo.toml`:

```toml
[dependencies]
hex = "0.4"
hmac = "0.12"
rand = "0.8"
reqwest = { version = "0.12", features = ["blocking"] }
serde_json = "1"
sha2 = "0.10"
```

```rust
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use std::time::{SystemTime, UNIX_EPOCH};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("CORTAD_INGEST_KEY")?;
    let body = serde_json::json!({
        "id": "conv_8f2c",
        "messages": [
            { "role": "user", "text": "Where is my order?", "at": "2026-11-08T14:02:11Z" },
            { "role": "assistant", "text": "It ships Monday.", "at": "2026-11-08T14:02:13Z" }
        ]
    })
    .to_string();
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis().to_string();
    let nonce = hex::encode(rand::random::<[u8; 16]>());
    let secret = hex::encode(Sha256::digest(key.as_bytes()));
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length");
    mac.update(format!("v1.{timestamp}.{nonce}.{}", hex::encode(Sha256::digest(body.as_bytes()))).as_bytes());
    let signature = hex::encode(mac.finalize().into_bytes());

    let response = reqwest::blocking::Client::new()
        .post("https://cortad.com/api/v1/conversations")
        .header("content-type", "application/json")
        .header("x-cortad-key", &key[..15])
        .header("x-cortad-timestamp", &timestamp)
        .header("x-cortad-nonce", &nonce)
        .header("x-cortad-signature", format!("v1={signature}"))
        .body(body)
        .send()?;
    let status = response.status();
    println!("{status} {}", response.text()?);
    Ok(())
}
```

### Edge runtimes

Web Crypto and `fetch` are all it takes on Cloudflare Workers, Vercel Edge Functions and Supabase Edge Functions. Call it from your handler through the platform's `waitUntil`, so the reply never waits on it: `ctx.waitUntil` on Cloudflare, `waitUntil` from `@vercel/functions` on Vercel, `EdgeRuntime.waitUntil` on Supabase.

```js
const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
const sha256Hex = async (text) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));

export async function sendConversation(key, conversation) {
  const body = JSON.stringify(conversation);
  const timestamp = String(Date.now());
  const nonce = hex(crypto.getRandomValues(new Uint8Array(16)));
  const secret = await crypto.subtle.importKey("raw", new TextEncoder().encode(await sha256Hex(key)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const signature = hex(await crypto.subtle.sign("HMAC", secret, new TextEncoder().encode(`v1.${timestamp}.${nonce}.${await sha256Hex(body)}`)));
  return fetch("https://cortad.com/api/v1/conversations", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-cortad-key": key.slice(0, 15),
      "x-cortad-timestamp": timestamp,
      "x-cortad-nonce": nonce,
      "x-cortad-signature": `v1=${signature}`,
    },
    body,
  });
}
```

On Cloudflare Workers:

```js
export default {
  async fetch(request, env, ctx) {
    const messages = [
      { role: "user", text: "Where is my order?", at: "2026-11-08T14:02:11Z" },
      { role: "assistant", text: "It ships Monday.", at: "2026-11-08T14:02:13Z" },
    ];
    ctx.waitUntil(sendConversation(env.CORTAD_INGEST_KEY, { id: "conv_8f2c", messages }));
    return new Response(messages.at(-1).text);
  },
};
```
