Two-way conversations

Receive and reply to texts, for a support inbox or an AI chatbot.

Two-way messaging lets customers text you back and get an answer. That answer can come from a person, from an AI chatbot, or from both, with the bot handling routine questions and handing the rest to staff.

Common uses:

  • AI support assistant: a model answers questions about orders, hours, or policies from your own data, and hands off to a person when it can't help or the customer asks.
  • Scheduling: a bot reads replies like "can we do Thursday instead?" and updates the booking.
  • Lead qualification: a bot asks a few questions and routes qualified leads to sales.
  • Shared inbox: staff read and reply to texts in your own app.

The steps below cover what every two-way integration needs: receiving texts, reading the thread, and replying. For a chatbot, your code sits between those: pass the thread to your model, then send its answer as the reply. Hand the conversation to staff when the model can't help.

When to use this guide

Use it when…Use something else when…
You want to read and answer customer texts: a support inbox, a sales line, or an AI chatbot.You only need a fixed reply to a reminder (for example C to confirm) → Appointment reminders
You only need to know when someone texts you → Webhooks

What you'll build

  1. Receive inbound texts in real time with a webhook.
  2. List conversations and read a thread.
  3. Reply, mark read, and archive.
  4. A polling fallback so nothing is lost if your webhook endpoint is down.

The model

A conversation is the thread between one of your numbers (userNumber) and one contact (contactNumber). It carries the contact's name, an unread count, opt-in/opt-out flags, archive state, and the last message.

Every outbound message you send to a contact and every inbound text they send you lands in the same thread, regardless of whether it was sent by the API, the web app, or a keyword auto-reply. Messages in a thread are listed oldest first by default, each marked READ or UNREAD.


Step 1: Receive texts with a webhook

Subscribe once to inbound_text.received:

curl -X POST https://a.eztexting.com/v1/webhooks/subscriptions \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "inbound_text.received",
    "callbackUrl": "https://support.example.com/webhooks/eztexting",
    "secret": "a-long-random-string"
  }'
import os, requests

auth = (os.environ["EZTEXTING_USERNAME"], os.environ["EZTEXTING_PASSWORD"])
requests.post(
    "https://a.eztexting.com/v1/webhooks/subscriptions",
    auth=auth,
    json={
        "type": "inbound_text.received",
        "callbackUrl": "https://support.example.com/webhooks/eztexting",
        "secret": os.environ["EZTEXTING_WEBHOOK_SECRET"],
    },
    timeout=30,
).raise_for_status()
const credentials = Buffer.from(
  `${process.env.EZTEXTING_USERNAME}:${process.env.EZTEXTING_PASSWORD}`
).toString("base64");

await fetch("https://a.eztexting.com/v1/webhooks/subscriptions", {
  method: "POST",
  headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    type: "inbound_text.received",
    callbackUrl: "https://support.example.com/webhooks/eztexting",
    secret: process.env.EZTEXTING_WEBHOOK_SECRET,
  }),
});
<?php
$ch = curl_init("https://a.eztexting.com/v1/webhooks/subscriptions");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
    CURLOPT_POSTFIELDS => json_encode([
        "type" => "inbound_text.received",
        "callbackUrl" => "https://support.example.com/webhooks/eztexting",
        "secret" => getenv("EZTEXTING_WEBHOOK_SECRET"),
    ]),
]);
curl_exec($ch);
curl_close($ch);
require "net/http"
require "json"

uri = URI("https://a.eztexting.com/v1/webhooks/subscriptions")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
req.body = {
  type: "inbound_text.received",
  callbackUrl: "https://support.example.com/webhooks/eztexting",
  secret: ENV.fetch("EZTEXTING_WEBHOOK_SECRET")
}.to_json
# raises unless 2xx
Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.value
String basicAuth = Base64.getEncoder().encodeToString(
    (System.getenv("EZTEXTING_USERNAME") + ":" + System.getenv("EZTEXTING_PASSWORD")).getBytes());
HttpClient client = HttpClient.newHttpClient();
// Jackson
ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(Map.of(
    "type", "inbound_text.received",
    "callbackUrl", "https://support.example.com/webhooks/eztexting",
    "secret", System.getenv("EZTEXTING_WEBHOOK_SECRET")));
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://a.eztexting.com/v1/webhooks/subscriptions"))
    .header("Authorization", "Basic " + basicAuth)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(json))
    .build();
client.send(request, HttpResponse.BodyHandlers.ofString());
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(
    $"{Environment.GetEnvironmentVariable("EZTEXTING_USERNAME")}:{Environment.GetEnvironmentVariable("EZTEXTING_PASSWORD")}"));
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

var res = await client.PostAsJsonAsync("https://a.eztexting.com/v1/webhooks/subscriptions", new
{
    type = "inbound_text.received",
    callbackUrl = "https://support.example.com/webhooks/eztexting",
    secret = Environment.GetEnvironmentVariable("EZTEXTING_WEBHOOK_SECRET")
});
res.EnsureSuccessStatusCode();
body, _ := json.Marshal(map[string]string{
	"type":        "inbound_text.received",
	"callbackUrl": "https://support.example.com/webhooks/eztexting",
	"secret":      os.Getenv("EZTEXTING_WEBHOOK_SECRET"),
})
req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/webhooks/subscriptions", bytes.NewReader(body))
req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
	panic(err)
}
resp.Body.Close()

Each inbound text arrives as a POST:

{
  "id": "128461504003",
  "type": "inbound_text.received",
  "fromNumber": "15551234567",
  "toNumber": "18885550199",
  "message": "Hi, I never received my order",
  "received": "2026-11-05T19:02:11.408+00:00",
  "optIn": false,
  "optOut": false
}

A minimal handler verifies the signature, acknowledges, and hands the message to your inbox:

import os, hmac, hashlib, base64
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["EZTEXTING_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/eztexting")
def inbound():
    expected = base64.b64encode(hmac.new(SECRET, request.get_data(), hashlib.sha256).digest()).decode()
    if not hmac.compare_digest(expected, request.headers.get("X-Signature-256", "")):
        abort(401)

    event = request.get_json()
    if event["type"] == "inbound_text.received":
        # your queue / DB
        inbox.enqueue(
            # message ID this text responds to; absent if none
            replies_to=event.get("id"),
            our_number=event["toNumber"],
            contact=event["fromNumber"],
            text=event["message"],
            received_at=event["received"],
            opted_out=event["optOut"],
        )
    return "", 204
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.EZTEXTING_WEBHOOK_SECRET;

app.post("/webhooks/eztexting", express.raw({ type: "application/json" }), async (req, res) => {
  const expected = crypto.createHmac("sha256", SECRET).update(req.body).digest("base64");
  const given = req.get("X-Signature-256") || "";
  if (expected.length !== given.length || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(given))) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body);
  if (event.type === "inbound_text.received") {
    // your queue / DB
    await inbox.enqueue({
      // message ID this text responds to; undefined if none
      repliesTo: event.id,
      ourNumber: event.toNumber,
      contact: event.fromNumber,
      text: event.message,
      receivedAt: event.received,
      optedOut: event.optOut,
    });
  }
  res.sendStatus(204);
});
<?php
$secret = getenv("EZTEXTING_WEBHOOK_SECRET");
$rawBody = file_get_contents("php://input");
$expected = base64_encode(hash_hmac("sha256", $rawBody, $secret, true));
if (!hash_equals($expected, $_SERVER["HTTP_X_SIGNATURE_256"] ?? "")) {
    http_response_code(401);
    exit;
}

$event = json_decode($rawBody, true);
if ($event['type'] === 'inbound_text.received') {
    // your queue / DB
    $inbox->enqueue([
        // message ID this text responds to; null if none
        'repliesTo'  => $event['id'] ?? null,
        'ourNumber'  => $event['toNumber'],
        'contact'    => $event['fromNumber'],
        'text'       => $event['message'],
        'receivedAt' => $event['received'],
        'optedOut'   => $event['optOut'],
    ]);
}
http_response_code(204);
class EzTextingWebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def create
    raw = request.raw_post
    expected = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", ENV.fetch("EZTEXTING_WEBHOOK_SECRET"), raw))
    given = request.headers["X-Signature-256"].to_s
    return head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(expected, given)

    event = JSON.parse(raw)
    if event["type"] == "inbound_text.received"
      # your queue / DB
      Inbox.enqueue(
        # message ID this text responds to; nil if none
        replies_to: event["id"],
        our_number: event["toNumber"],
        contact: event["fromNumber"],
        text: event["message"],
        received_at: event["received"],
        opted_out: event["optOut"]
      )
    end
    head :no_content
  end
end
@PostMapping("/webhooks/eztexting")
public ResponseEntity<Void> inbound(@RequestBody byte[] rawBody,
                                    @RequestHeader(value = "X-Signature-256", required = false) String given) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(System.getenv("EZTEXTING_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String expected = Base64.getEncoder().encodeToString(mac.doFinal(rawBody));
    if (given == null || !MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), given.getBytes(StandardCharsets.UTF_8))) {
        return ResponseEntity.status(401).build();
    }

    JsonNode event = mapper.readTree(rawBody);
    if ("inbound_text.received".equals(event.path("type").asText())) {
        // your queue / DB
        inbox.enqueue(new InboundText(
            // message ID this text responds to; null if none
            event.path("id").asText(null),
            event.get("toNumber").asText(),
            event.get("fromNumber").asText(),
            event.get("message").asText(),
            event.get("received").asText(),
            event.get("optOut").asBoolean()));
    }
    return ResponseEntity.noContent().build();
}
app.MapPost("/webhooks/eztexting", async (HttpRequest req, IInbox inbox) =>
{
    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    var rawBody = ms.ToArray();

    var key = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("EZTEXTING_WEBHOOK_SECRET")!);
    var expected = Convert.ToBase64String(HMACSHA256.HashData(key, rawBody));
    var given = req.Headers["X-Signature-256"].ToString();
    if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given)))
        return Results.Unauthorized();

    var evt = JsonDocument.Parse(rawBody).RootElement;
    if (evt.GetProperty("type").GetString() == "inbound_text.received")
    {
        // your queue / DB
        await inbox.EnqueueAsync(new InboundText(
            // message ID this text responds to; null if none
            RepliesTo: evt.TryGetProperty("id", out var id) ? id.GetString() : null,
            OurNumber: evt.GetProperty("toNumber").GetString()!,
            Contact: evt.GetProperty("fromNumber").GetString()!,
            Text: evt.GetProperty("message").GetString()!,
            ReceivedAt: evt.GetProperty("received").GetString()!,
            OptedOut: evt.GetProperty("optOut").GetBoolean()));
    }
    return Results.NoContent();
});
func inbound(w http.ResponseWriter, r *http.Request) {
	rawBody, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	mac := hmac.New(sha256.New, []byte(os.Getenv("EZTEXTING_WEBHOOK_SECRET")))
	mac.Write(rawBody)
	expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
	if !hmac.Equal([]byte(expected), []byte(r.Header.Get("X-Signature-256"))) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	var event struct {
		ID         string `json:"id"`
		Type       string `json:"type"`
		FromNumber string `json:"fromNumber"`
		ToNumber   string `json:"toNumber"`
		Message    string `json:"message"`
		Received   string `json:"received"`
		OptOut     bool   `json:"optOut"`
	}
	json.Unmarshal(rawBody, &event)
	if event.Type == "inbound_text.received" {
		// your queue / DB
		inbox.Enqueue(InboundText{
			// message ID this text responds to; empty if none
			RepliesTo:  event.ID,
			OurNumber:  event.ToNumber,
			Contact:    event.FromNumber,
			Text:       event.Message,
			ReceivedAt: event.Received,
			OptedOut:   event.OptOut,
		})
	}
	w.WriteHeader(http.StatusNoContent)
}

Step 2: List conversations and read a thread

For an inbox view, list conversations, unread first:

curl -G https://a.eztexting.com/v1/conversations \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  --data-urlencode "filters[unread][eq]=true" \
  --data-urlencode "size=50"
convos = requests.get(
    "https://a.eztexting.com/v1/conversations",
    auth=auth,
    params={"filters[unread][eq]": "true", "size": 50},
    timeout=30,
).json()
for c in convos["content"]:
    # contactName is omitted when the contact has no name
    print(c["contactNumber"], c.get("contactName", ""), c["unreadCount"], c["lastMessage"]["message"])
const convos = await (await fetch("https://a.eztexting.com/v1/conversations?filters[unread][eq]=true&size=50", {
  headers: { Authorization: `Basic ${credentials}` },
})).json();
for (const c of convos.content) {
  console.log(c.contactNumber, c.contactName, c.unreadCount, c.lastMessage.message);
}
<?php
$qs = http_build_query(["filters[unread][eq]" => "true", "size" => 50]);
$ch = curl_init("https://a.eztexting.com/v1/conversations?$qs");
curl_setopt($ch, CURLOPT_USERPWD, getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$convos = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach ($convos['content'] as $c) {
    echo "{$c['contactNumber']} " . ($c['contactName'] ?? '') . " {$c['unreadCount']} {$c['lastMessage']['message']}\n";
}
uri = URI("https://a.eztexting.com/v1/conversations")
uri.query = URI.encode_www_form("filters[unread][eq]" => "true", "size" => 50)
req = Net::HTTP::Get.new(uri)
req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
convos = JSON.parse(Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.body)
convos["content"].each do |c|
  puts [c["contactNumber"], c["contactName"], c["unreadCount"], c["lastMessage"]["message"]].join(" ")
end
String qs = URLEncoder.encode("filters[unread][eq]", StandardCharsets.UTF_8) + "=true&size=50";
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://a.eztexting.com/v1/conversations?" + qs))
    .header("Authorization", "Basic " + basicAuth)
    .GET().build();
JsonNode convos = mapper.readTree(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
for (JsonNode c : convos.get("content")) {
    System.out.println(c.get("contactNumber").asText() + " " + c.path("contactName").asText("") + " "
        + c.get("unreadCount").asInt() + " " + c.get("lastMessage").get("message").asText());
}
var qs = $"{Uri.EscapeDataString("filters[unread][eq]")}=true&size=50";
var convos = await client.GetFromJsonAsync<JsonElement>($"https://a.eztexting.com/v1/conversations?{qs}");
foreach (var c in convos.GetProperty("content").EnumerateArray())
{
    var name = c.TryGetProperty("contactName", out var n) ? n.GetString() : "";
    Console.WriteLine($"{c.GetProperty("contactNumber")} {name} {c.GetProperty("unreadCount")} {c.GetProperty("lastMessage").GetProperty("message")}");
}
q := url.Values{"filters[unread][eq]": {"true"}, "size": {"50"}}
req, _ := http.NewRequest("GET", "https://a.eztexting.com/v1/conversations?"+q.Encode(), nil)
req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
var convos struct {
	Content []struct {
		ContactNumber string `json:"contactNumber"`
		ContactName   string `json:"contactName"`
		UnreadCount   int    `json:"unreadCount"`
		LastMessage   struct {
			Message string `json:"message"`
		} `json:"lastMessage"`
	} `json:"content"`
}
json.NewDecoder(resp.Body).Decode(&convos)
for _, c := range convos.Content {
	fmt.Println(c.ContactNumber, c.ContactName, c.UnreadCount, c.LastMessage.Message)
}
{
  "content": [
    {
      "userNumber": "18885550199",
      "contactNumber": "15551234567",
      "contactName": "Jane Doe",
      "unreadCount": 2,
      "optIn": false,
      "optOut": false,
      "archived": false,
      "lastMessage": {
        "inbound": true,
        "message": "Hi, I never received my order",
        "sentAt": "2026-11-05T19:02:11.408Z"
      }
    }
  ],
  "number": 0,
  "size": 50,
  "totalElements": 1,
  "totalPages": 1,
  "numberOfElements": 1
}

Other useful filters: filters[archived][eq]=true, filters[optType][eq]=optOut, and filters[query][eq]= for free-text search across name, number, and last message. (All list filters use this bracket syntax. See Pagination, filtering & sorting.)

To open a thread, fetch its messages:

curl "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50" \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD"
thread = requests.get(
    "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567",
    auth=auth,
    params={"size": 50},
    timeout=30,
).json()
for m in thread["content"]:
    who = "them" if m["inbound"] else "us"
    print(m["sentAt"], who, m["status"], m["message"])
const thread = await (await fetch(
  "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50",
  { headers: { Authorization: `Basic ${credentials}` } }
)).json();
for (const m of thread.content) {
  console.log(m.sentAt, m.inbound ? "them" : "us", m.status, m.message);
}
<?php
$ch = curl_init("https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50");
curl_setopt($ch, CURLOPT_USERPWD, getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$thread = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach ($thread['content'] as $m) {
    $who = $m['inbound'] ? 'them' : 'us';
    echo "{$m['sentAt']} $who {$m['status']} {$m['message']}\n";
}
uri = URI("https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50")
req = Net::HTTP::Get.new(uri)
req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
thread = JSON.parse(Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.body)
thread["content"].each do |m|
  puts [m["sentAt"], m["inbound"] ? "them" : "us", m["status"], m["message"]].join(" ")
end
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50"))
    .header("Authorization", "Basic " + basicAuth)
    .GET().build();
JsonNode thread = mapper.readTree(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
for (JsonNode m : thread.get("content")) {
    System.out.println(m.get("sentAt").asText() + " " + (m.get("inbound").asBoolean() ? "them" : "us") + " "
        + m.get("status").asText() + " " + m.get("message").asText());
}
var thread = await client.GetFromJsonAsync<JsonElement>(
    "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50");
foreach (var m in thread.GetProperty("content").EnumerateArray())
{
    var who = m.GetProperty("inbound").GetBoolean() ? "them" : "us";
    Console.WriteLine($"{m.GetProperty("sentAt")} {who} {m.GetProperty("status")} {m.GetProperty("message")}");
}
req, _ := http.NewRequest("GET", "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567?size=50", nil)
req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
var thread struct {
	Content []struct {
		ID      string `json:"id"`
		Inbound bool   `json:"inbound"`
		Message string `json:"message"`
		SentAt  string `json:"sentAt"`
		Status  string `json:"status"`
	} `json:"content"`
}
json.NewDecoder(resp.Body).Decode(&thread)
for _, m := range thread.Content {
	who := "us"
	if m.Inbound {
		who = "them"
	}
	fmt.Println(m.SentAt, who, m.Status, m.Message)
}
{
  "id": "EZ_420000064734507008_18885550199_15551234567_20261105190211_1440252137",
  "userNumber": "18885550199",
  "contactNumber": "15551234567",
  "inbound": true,
  "message": "Hi, I never received my order",
  "sentAt": "2026-11-05T19:02:11.408Z",
  "optIn": false,
  "optOut": false,
  "status": "UNREAD",
  "type": "SMS",
  "group": false
}

Fields without a value are left out, not returned as null: mediaUrl appears only on MMS, contactName only when the contact has a name, and messageGroupId only when the message belongs to (or replies to) a send.


Step 3: Reply, mark read, archive

Reply is just a send to that contact. Pass fromNumber so the reply comes from the same number the customer texted (important if your account has several):

curl -X POST https://a.eztexting.com/v1/messages \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "fromNumber": "18885550199",
    "toNumbers": ["15551234567"],
    "message": "Sorry about that, Jane — looking into order #A1234 now. Can you confirm the shipping address?"
  }'
def reply(our_number, contact, text):
    requests.post(
        "https://a.eztexting.com/v1/messages",
        auth=auth,
        json={"fromNumber": our_number, "toNumbers": [contact], "message": text},
        timeout=30,
    ).raise_for_status()
async function reply(ourNumber, contact, text) {
  const res = await fetch("https://a.eztexting.com/v1/messages", {
    method: "POST",
    headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
    body: JSON.stringify({ fromNumber: ourNumber, toNumbers: [contact], message: text }),
  });
  if (!res.ok) throw new Error(`EZ Texting ${res.status}`);
}
<?php
function reply(string $ourNumber, string $contact, string $text): void {
    $ch = curl_init("https://a.eztexting.com/v1/messages");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode(["fromNumber" => $ourNumber, "toNumbers" => [$contact], "message" => $text]),
    ]);
    curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status !== 201) throw new RuntimeException("EZ Texting $status");
}
def reply(our_number, contact, text)
  uri = URI("https://a.eztexting.com/v1/messages")
  req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  req.body = { fromNumber: our_number, toNumbers: [contact], message: text }.to_json
  # raises unless 2xx
  Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.value
end
void reply(String ourNumber, String contact, String text) throws Exception {
    String json = mapper.writeValueAsString(
        Map.of("fromNumber", ourNumber, "toNumbers", List.of(contact), "message", text));
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/messages"))
        .header("Authorization", "Basic " + basicAuth)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() != 201) throw new RuntimeException("EZ Texting " + response.statusCode());
}
async Task ReplyAsync(string ourNumber, string contact, string text)
{
    var res = await client.PostAsJsonAsync("https://a.eztexting.com/v1/messages",
        new { fromNumber = ourNumber, toNumbers = new[] { contact }, message = text });
    res.EnsureSuccessStatusCode();
}
func reply(ourNumber, contact, text string) error {
	body, _ := json.Marshal(map[string]any{"fromNumber": ourNumber, "toNumbers": []string{contact}, "message": text})
	req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/messages", bytes.NewReader(body))
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	if resp.StatusCode != 201 {
		return fmt.Errorf("EZ Texting %d", resp.StatusCode)
	}
	return nil
}

Mark read when an agent opens the thread, so unread counts stay meaningful across the API and the web app:

curl -X POST https://a.eztexting.com/v1/conversations/messages/read \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{"idList": ["EZ_420000064734507008_18885550199_15551234567_20261105190211_1440252137"]}'
unread_ids = [m["id"] for m in thread["content"] if m["inbound"] and m["status"] == "UNREAD"]
requests.post(
    "https://a.eztexting.com/v1/conversations/messages/read",
    auth=auth,
    json={"idList": unread_ids},
    timeout=30,
).raise_for_status()
const unreadIds = thread.content.filter((m) => m.inbound && m.status === "UNREAD").map((m) => m.id);
await fetch("https://a.eztexting.com/v1/conversations/messages/read", {
  method: "POST",
  headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
  body: JSON.stringify({ idList: unreadIds }),
});
<?php
$unreadIds = [];
foreach ($thread['content'] as $m) {
    if ($m['inbound'] && $m['status'] === 'UNREAD') $unreadIds[] = $m['id'];
}
$ch = curl_init("https://a.eztexting.com/v1/conversations/messages/read");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
    CURLOPT_POSTFIELDS => json_encode(["idList" => $unreadIds]),
]);
curl_exec($ch);
curl_close($ch);
unread_ids = thread["content"].select { |m| m["inbound"] && m["status"] == "UNREAD" }.map { |m| m["id"] }
uri = URI("https://a.eztexting.com/v1/conversations/messages/read")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
req.body = { idList: unread_ids }.to_json
# raises unless 2xx
Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.value
List<String> unreadIds = new ArrayList<>();
for (JsonNode m : thread.get("content")) {
    if (m.get("inbound").asBoolean() && "UNREAD".equals(m.get("status").asText())) unreadIds.add(m.get("id").asText());
}
HttpRequest markRead = HttpRequest.newBuilder()
    .uri(URI.create("https://a.eztexting.com/v1/conversations/messages/read"))
    .header("Authorization", "Basic " + basicAuth)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(Map.of("idList", unreadIds))))
    .build();
client.send(markRead, HttpResponse.BodyHandlers.ofString());
var unreadIds = thread.GetProperty("content").EnumerateArray()
    .Where(m => m.GetProperty("inbound").GetBoolean() && m.GetProperty("status").GetString() == "UNREAD")
    .Select(m => m.GetProperty("id").GetString())
    .ToArray();
var res = await client.PostAsJsonAsync("https://a.eztexting.com/v1/conversations/messages/read", new { idList = unreadIds });
res.EnsureSuccessStatusCode();
var unreadIDs []string
for _, m := range thread.Content {
	if m.Inbound && m.Status == "UNREAD" {
		unreadIDs = append(unreadIDs, m.ID)
	}
}
body, _ := json.Marshal(map[string][]string{"idList": unreadIDs})
req, _ = http.NewRequest("POST", "https://a.eztexting.com/v1/conversations/messages/read", bytes.NewReader(body))
req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
req.Header.Set("Content-Type", "application/json")
resp, err = http.DefaultClient.Do(req)
if err != nil {
	panic(err)
}
resp.Body.Close()

The IDs in idList are the per-message id values from the thread (the EZ_… individual message IDs), not the message ID; the message ID returns 200 and changes nothing. (/messages/unread with the same body flips them back. Alternatively, add ?read=true when fetching a thread to mark everything in it read in the same call.)

Archive when the issue is resolved; restore if the customer writes again:

curl -X POST https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567/archive \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD"

curl -X POST https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567/restore \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD"
thread_url = "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567"
# resolved
requests.post(f"{thread_url}/archive", auth=auth, timeout=30).raise_for_status()
# customer wrote again
requests.post(f"{thread_url}/restore", auth=auth, timeout=30).raise_for_status()
const threadUrl = "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567";
const auth = { Authorization: `Basic ${credentials}` };
// resolved
await fetch(`${threadUrl}/archive`, { method: "POST", headers: auth });
// customer wrote again
await fetch(`${threadUrl}/restore`, { method: "POST", headers: auth });
<?php
// "archive" or "restore"
function threadAction(string $ourNumber, string $contact, string $action): void {
    $ch = curl_init("https://a.eztexting.com/v1/conversations/conversation/$ourNumber/$contact/$action");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// resolved
threadAction("18885550199", "15551234567", "archive");
// customer wrote again
threadAction("18885550199", "15551234567", "restore");
# "archive" or "restore"
def thread_action(our_number, contact, action)
  uri = URI("https://a.eztexting.com/v1/conversations/conversation/#{our_number}/#{contact}/#{action}")
  req = Net::HTTP::Post.new(uri)
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  # raises unless 2xx
  Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }.value
end

# resolved
thread_action("18885550199", "15551234567", "archive")
# customer wrote again
thread_action("18885550199", "15551234567", "restore")
// "archive" or "restore"
void threadAction(String ourNumber, String contact, String action) throws Exception {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/conversations/conversation/" + ourNumber + "/" + contact + "/" + action))
        .header("Authorization", "Basic " + basicAuth)
        .POST(HttpRequest.BodyPublishers.noBody())
        .build();
    client.send(request, HttpResponse.BodyHandlers.ofString());
}

// resolved
threadAction("18885550199", "15551234567", "archive");
// customer wrote again
threadAction("18885550199", "15551234567", "restore");
const string threadUrl = "https://a.eztexting.com/v1/conversations/conversation/18885550199/15551234567";
// resolved
(await client.PostAsync($"{threadUrl}/archive", null)).EnsureSuccessStatusCode();
// customer wrote again
(await client.PostAsync($"{threadUrl}/restore", null)).EnsureSuccessStatusCode();
// "archive" or "restore"
func threadAction(ourNumber, contact, action string) error {
	req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/conversations/conversation/"+ourNumber+"/"+contact+"/"+action, nil)
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}

// resolved
threadAction("18885550199", "15551234567", "archive")
// customer wrote again
threadAction("18885550199", "15551234567", "restore")

Step 4: Polling fallback

Webhooks are the primary path, but your endpoint will be down sometimes (a deploy, an outage, an expired certificate). Run a periodic sweep so nothing is silently lost:

def sweep_unread():
    page = 0
    while True:
        convos = requests.get(
            "https://a.eztexting.com/v1/conversations",
            auth=auth, params={"filters[unread][eq]": "true", "size": 200, "page": page},
            timeout=30,
        ).json()
        for c in convos["content"]:
            sweep_thread(c["userNumber"], c["contactNumber"], c["unreadCount"])
        if page + 1 >= convos["totalPages"]:
            break
        page += 1


def sweep_thread(user_number, contact_number, unread):
    # newest first; stop when every unread text is found or the thread ends
    page = 0
    while unread > 0:
        thread = requests.get(
            f"https://a.eztexting.com/v1/conversations/conversation/USER_NUMBER/{contact_number}",
            auth=auth, params={"size": 50, "sort": "created,desc", "page": page},
            timeout=30,
        ).json()
        for m in thread["content"]:
            if m["inbound"] and m["status"] == "UNREAD":
                unread -= 1
                # skip if the webhook already stored it
                inbox.enqueue_if_new(m["id"], m)
        if page + 1 >= thread["totalPages"]:
            break
        page += 1
async function ezGet(pathAndQuery) {
  const res = await fetch(`https://a.eztexting.com${pathAndQuery}`, {
    headers: { Authorization: `Basic ${credentials}` },
    signal: AbortSignal.timeout(30_000),
  });
  return res.json();
}

async function sweepUnread() {
  for (let page = 0; ; page++) {
    const convos = await ezGet(`/v1/conversations?filters[unread][eq]=true&size=200&page=${page}`);
    for (const c of convos.content) {
      await sweepThread(c.userNumber, c.contactNumber, c.unreadCount);
    }
    if (page + 1 >= convos.totalPages) break;
  }
}

async function sweepThread(userNumber, contactNumber, unread) {
  // newest first; stop when every unread text is found or the thread ends
  for (let page = 0; unread > 0; page++) {
    const thread = await ezGet(
      `/v1/conversations/conversation/$USERNUMBER/${contactNumber}?size=50&sort=created,desc&page=${page}`
    );
    for (const m of thread.content) {
      if (m.inbound && m.status === "UNREAD") {
        unread--;
        // skip if the webhook already stored it
        await inbox.enqueueIfNew(m.id, m);
      }
    }
    if (page + 1 >= thread.totalPages) break;
  }
}
<?php
function ezGet(string $path, array $params = []): array {
    $ch = curl_init("https://a.eztexting.com$path?" . http_build_query($params));
    curl_setopt($ch, CURLOPT_USERPWD, getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $data = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $data;
}

function sweepUnread(): void {
    for ($page = 0; ; $page++) {
        $convos = ezGet("/v1/conversations", ["filters[unread][eq]" => "true", "size" => 200, "page" => $page]);
        foreach ($convos['content'] as $c) {
            sweepThread($c['userNumber'], $c['contactNumber'], $c['unreadCount']);
        }
        if ($page + 1 >= $convos['totalPages']) break;
    }
}

function sweepThread(string $userNumber, string $contactNumber, int $unread): void {
    global $inbox;
    // newest first; stop when every unread text is found or the thread ends
    for ($page = 0; $unread > 0; $page++) {
        $thread = ezGet("/v1/conversations/conversation/$userNumber/$contactNumber",
            ["size" => 50, "sort" => "created,desc", "page" => $page]);
        foreach ($thread['content'] as $m) {
            if ($m['inbound'] && $m['status'] === 'UNREAD') {
                $unread--;
                // skip if the webhook already stored it
                $inbox->enqueueIfNew($m['id'], $m);
            }
        }
        if ($page + 1 >= $thread['totalPages']) break;
    }
}
def ez_get(path, params = {})
  uri = URI("https://a.eztexting.com#{path}")
  uri.query = URI.encode_www_form(params)
  req = Net::HTTP::Get.new(uri)
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
    http.request(req)
  end
  JSON.parse(res.body)
end

def sweep_unread
  page = 0
  loop do
    convos = ez_get("/v1/conversations", "filters[unread][eq]" => "true", "size" => 200, "page" => page)
    convos["content"].each do |c|
      sweep_thread(c["userNumber"], c["contactNumber"], c["unreadCount"])
    end
    break if page + 1 >= convos["totalPages"]
    page += 1
  end
end

def sweep_thread(user_number, contact_number, unread)
  # newest first; stop when every unread text is found or the thread ends
  page = 0
  while unread > 0
    thread = ez_get("/v1/conversations/conversation/#USER_NUMBER/#{contact_number}",
                    "size" => 50, "sort" => "created,desc", "page" => page)
    thread["content"].each do |m|
      next unless m["inbound"] && m["status"] == "UNREAD"
      unread -= 1
      # skip if the webhook already stored it
      Inbox.enqueue_if_new(m["id"], m)
    end
    break if page + 1 >= thread["totalPages"]
    page += 1
  end
end
JsonNode ezGet(String pathAndQuery) throws Exception {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com" + pathAndQuery))
        .header("Authorization", "Basic " + basicAuth)
        .timeout(Duration.ofSeconds(30))
        .GET().build();
    return mapper.readTree(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
}

void sweepUnread() throws Exception {
    String unread = URLEncoder.encode("filters[unread][eq]", StandardCharsets.UTF_8) + "=true";
    for (int page = 0; ; page++) {
        JsonNode convos = ezGet("/v1/conversations?" + unread + "&size=200&page=" + page);
        for (JsonNode c : convos.get("content")) {
            sweepThread(c.get("userNumber").asText(), c.get("contactNumber").asText(), c.get("unreadCount").asInt());
        }
        if (page + 1 >= convos.get("totalPages").asInt()) break;
    }
}

void sweepThread(String userNumber, String contactNumber, int unread) throws Exception {
    // newest first; stop when every unread text is found or the thread ends
    for (int page = 0; unread > 0; page++) {
        JsonNode thread = ezGet("/v1/conversations/conversation/" + userNumber + "/" + contactNumber
            + "?size=50&sort=created,desc&page=" + page);
        for (JsonNode m : thread.get("content")) {
            if (m.get("inbound").asBoolean() && "UNREAD".equals(m.get("status").asText())) {
                unread--;
                // skip if the webhook already stored it
                inbox.enqueueIfNew(m.get("id").asText(), m);
            }
        }
        if (page + 1 >= thread.get("totalPages").asInt()) break;
    }
}
async Task SweepUnreadAsync()
{
    var unread = $"{Uri.EscapeDataString("filters[unread][eq]")}=true";
    for (var page = 0; ; page++)
    {
        var convos = await client.GetFromJsonAsync<JsonElement>(
            $"https://a.eztexting.com/v1/conversations?{unread}&size=200&page={page}");
        foreach (var c in convos.GetProperty("content").EnumerateArray())
        {
            await SweepThreadAsync(c.GetProperty("userNumber").GetString()!,
                c.GetProperty("contactNumber").GetString()!, c.GetProperty("unreadCount").GetInt32());
        }
        if (page + 1 >= convos.GetProperty("totalPages").GetInt32()) break;
    }
}

async Task SweepThreadAsync(string userNumber, string contactNumber, int unread)
{
    // newest first; stop when every unread text is found or the thread ends
    for (var page = 0; unread > 0; page++)
    {
        var thread = await client.GetFromJsonAsync<JsonElement>(
            $"https://a.eztexting.com/v1/conversations/conversation/USERNUMBER/{contactNumber}?size=50&sort=created,desc&page={page}");
        foreach (var m in thread.GetProperty("content").EnumerateArray())
        {
            if (m.GetProperty("inbound").GetBoolean() && m.GetProperty("status").GetString() == "UNREAD")
            {
                unread--;
                // skip if the webhook already stored it
                await inbox.EnqueueIfNewAsync(m.GetProperty("id").GetString()!, m);
            }
        }
        if (page + 1 >= thread.GetProperty("totalPages").GetInt32()) break;
    }
}
var ezClient = &http.Client{Timeout: 30 * time.Second}

func ezGet(path string, q url.Values, out any) error {
	req, _ := http.NewRequest("GET", "https://a.eztexting.com"+path+"?"+q.Encode(), nil)
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	resp, err := ezClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	return json.NewDecoder(resp.Body).Decode(out)
}

func sweepUnread() error {
	for page := 0; ; page++ {
		var convos struct {
			Content []struct {
				UserNumber    string `json:"userNumber"`
				ContactNumber string `json:"contactNumber"`
				UnreadCount   int    `json:"unreadCount"`
			} `json:"content"`
			TotalPages int `json:"totalPages"`
		}
		q := url.Values{"filters[unread][eq]": {"true"}, "size": {"200"}, "page": {strconv.Itoa(page)}}
		if err := ezGet("/v1/conversations", q, &convos); err != nil {
			return err
		}
		for _, c := range convos.Content {
			if err := sweepThread(c.UserNumber, c.ContactNumber, c.UnreadCount); err != nil {
				return err
			}
		}
		if page+1 >= convos.TotalPages {
			return nil
		}
	}
}

func sweepThread(userNumber, contactNumber string, unread int) error {
	// newest first; stop when every unread text is found or the thread ends
	for page := 0; unread > 0; page++ {
		var thread struct {
			Content    []map[string]any `json:"content"`
			TotalPages int              `json:"totalPages"`
		}
		q := url.Values{"size": {"50"}, "sort": {"created,desc"}, "page": {strconv.Itoa(page)}}
		if err := ezGet("/v1/conversations/conversation/"+userNumber+"/"+contactNumber, q, &thread); err != nil {
			return err
		}
		for _, m := range thread.Content {
			if m["inbound"] == true && m["status"] == "UNREAD" {
				unread--
				// skip if the webhook already stored it
				inbox.EnqueueIfNew(m["id"].(string), m)
			}
		}
		if page+1 >= thread.TotalPages {
			return nil
		}
	}
	return nil
}

Threads are oldest first by default, so each thread is fetched newest first (sort=created,desc). The conversation's unreadCount says how many unread texts to look for; the sweep pages back through the thread until it has found them all or reaches the start of the thread, so a burst of more than 50 replies isn't cut off. Every few minutes is plenty. Webhook payloads don't carry the thread message id, so before enqueuing a swept text, check whether your webhook already stored it (same contact, same number, same text).


Handling STOP, HELP, and keywords

  • STOP (and UNSUBSCRIBE, QUIT, END, CANCEL, REMOVE) is handled by EZ Texting: the contact is marked optOut: true and the platform won't deliver further messages, including your agent's replies. The inbound text still reaches your webhook with optOut: true, so you can close the thread in your UI and stop assigning it.
  • HELP replies are also handled at the platform level. You don't need to answer them.
  • Keywords you've configured (for example, JOIN) trigger their own auto-reply and, if subscribed, a keyword.opt_in webhook. They arrive as inbound texts too; if your inbox shouldn't treat them as conversations, filter on the keyword text.

Gotchas

  • Reply from the right number. If your account has several numbers, always set fromNumber to the toNumber from the inbound payload. A reply from a different number starts a different thread on the customer's phone.
  • Webhook auto-disable. Repeated delivery failures to your callbackUrl can cause EZ Texting to stop calling it. After any outage, check GET /v1/webhooks/subscriptions and re-create if needed, and let the sweep catch up.
  • Media. Inbound MMS arrives with a mediaUrl in the message object when you read the thread. Download it promptly if you need to keep it.
  • Thread identity. A conversation is keyed by your number + their number. The same customer texting two of your numbers is two conversations.

Related

API reference


Did this page help you?