One call to send. One webhook to hear back.
A small, plain API over HTTPS and JSON, with a contract you can generate a client from.
# Send "Is this test working?", with Yes and No, to your own phone. Keep the message_id it prints.
curl -s "${API_URL:-https://api.greenmessage.app}/v1/messages" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{ "recipients": [{ "to": "$TO" }], "body": "Is this test working?", "response": "confirm" }
EOF
# 202 Accepted
{ "results": [{ "to": "+447400123456", "status": "accepted",
"message_id": "msg_01JCA7Q2KB…" }] }TO is the number of the phone where you installed GreenMessage, and API_KEY a key you make in the console. Your first message, step by step
Start here
Your first message, in five minutes.
Once we have approved your business, test it with your own phone: the question arrives in GreenMessage there, you tap an answer, and your code prints it.
- Get the app on your phone, from the App Store or Google Play, and sign in with your mobile number.
- Add that phone as a test number in the console, and tap Allow when the app asks. Then make a test key: it reaches only your test numbers, so you cannot message a customer by accident.
- Set three values where you run the examples, so that none of them holds your key:
API_KEY, the key;TO, the number of your phone;API_URL,https://api.greenmessage.app. - Send a question to your phone with an example below, and tap Yes on the phone. The example prints each state as the message moves, then
Answered: yes. - Hear answers as they happen at a webhook of your own. Each example checks the signature on every delivery, and refuses one that does not hold.
Send it, and keep the message_id it prints curl/send.sh
# Send "Is this test working?", with Yes and No, to your own phone. Keep the message_id it prints.
curl -s "${API_URL:-https://api.greenmessage.app}/v1/messages" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{ "recipients": [{ "to": "$TO" }], "body": "Is this test working?", "response": "confirm" }
EOFCheck it: its state, and your answer once you have tapped it curl/check.sh
# Check it: its state, and your answer once you have tapped it. MESSAGE_ID is the one the send printed.
curl -s "${API_URL:-https://api.greenmessage.app}/v1/messages/$MESSAGE_ID" \
-H "Authorization: Bearer $API_KEY"Send it, and wait for your answer node/first-message.mjs
// Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
// Node 18 or later, nothing to install: node first-message.mjs
// API_KEY and TO (your mobile number) come from the environment.
const api = process.env.API_URL ?? 'https://api.greenmessage.app';
const headers = { Authorization: `Bearer ${process.env.API_KEY}`, 'Content-Type': 'application/json' };
const sent = await fetch(`${api}/v1/messages`, {
method: 'POST',
headers,
body: JSON.stringify({ recipients: [{ to: process.env.TO }], body: 'Is this test working?', response: 'confirm' }),
}).then((res) => res.json());
const result = sent.results?.[0];
if (result?.status !== 'accepted') {
console.error('Not sent:', JSON.stringify(sent));
process.exit(1);
}
console.log(`Sent ${result.message_id}. Answer it on your phone.`);
let last = '';
for (let i = 0; i < 60; i++) {
const message = await fetch(`${api}/v1/messages/${result.message_id}`, { headers }).then((res) => res.json());
if (message.state !== last) console.log(`State: ${(last = message.state)}`);
if (message.state === 'answered') {
console.log(`Answered: ${message.answer}`);
process.exit(0);
}
if (['expired', 'failed', 'cancelled'].includes(message.state)) process.exit(1);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
console.error('No answer within two minutes.');
process.exit(1);Hear the answer at your webhook node/webhook.mjs
// Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
// delivery. Node 18 or later, nothing to install: node webhook.mjs
// WEBHOOK_SECRET is the secret shown when you added the endpoint; PORT is where it listens.
import { createServer } from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';
// signed says whether the GM-Signature header signs this raw body with your secret, within five minutes.
function signed(header = '', body) {
const parts = Object.fromEntries(header.split(',').map((part) => part.split('=', 2)));
if (!(Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300) || !parts.v1) return false;
const want = createHmac('sha256', process.env.WEBHOOK_SECRET).update(`${parts.t}.`).update(body).digest();
const got = Buffer.from(parts.v1, 'hex');
return got.length === want.length && timingSafeEqual(got, want);
}
const port = Number(process.env.PORT ?? 8099);
createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks);
if (!signed(req.headers['gm-signature'], body)) {
console.log('Refused a delivery: its signature does not hold');
res.writeHead(401).end();
return;
}
const { type, data } = JSON.parse(body);
console.log(`Heard ${type} for ${data.id}: ${data.state}${data.answer ? `, ${data.answer}` : ''}`);
res.writeHead(200).end();
});
}).listen(port, '127.0.0.1', () => console.log(`Listening on http://127.0.0.1:${port}`));Send it, and wait for your answer python/first_message.py
# Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
# Python 3.8 or later, nothing to install: python3 first_message.py
# API_KEY and TO (your mobile number) come from the environment.
import json
import os
import sys
import time
import urllib.error
import urllib.request
API = os.environ.get("API_URL", "https://api.greenmessage.app")
HEADERS = {"Authorization": "Bearer " + os.environ["API_KEY"], "Content-Type": "application/json"}
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(API + path, data=data, headers=HEADERS, method=method)
try:
with urllib.request.urlopen(request) as response:
return json.load(response)
except urllib.error.HTTPError as error:
return json.load(error)
sent = call("POST", "/v1/messages", {"recipients": [{"to": os.environ["TO"]}],
"body": "Is this test working?", "response": "confirm"})
result = (sent.get("results") or [{}])[0]
if result.get("status") != "accepted":
sys.exit("Not sent: " + json.dumps(sent))
print(f"Sent {result['message_id']}. Answer it on your phone.", flush=True)
last = ""
for _ in range(60):
message = call("GET", "/v1/messages/" + result["message_id"])
if message["state"] != last:
last = message["state"]
print("State:", last, flush=True)
if last == "answered":
print("Answered:", message["answer"], flush=True)
sys.exit(0)
if last in ("expired", "failed", "cancelled"):
sys.exit(1)
time.sleep(2)
sys.exit("No answer within two minutes.")Hear the answer at your webhook python/webhook.py
# Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
# delivery. Python 3.8 or later, nothing to install: python3 webhook.py
# WEBHOOK_SECRET is the secret shown when you added the endpoint; PORT is where it listens.
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["WEBHOOK_SECRET"].encode()
def signed(header, body):
"""Whether the GM-Signature header signs this raw body with your secret, within five minutes."""
parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
if not parts.get("t", "").isdigit() or abs(time.time() - int(parts["t"])) > 300:
return False
want = hmac.new(SECRET, parts["t"].encode() + b"." + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(want, parts.get("v1", ""))
class Webhook(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if not signed(self.headers.get("GM-Signature", ""), body):
print("Refused a delivery: its signature does not hold", flush=True)
self.send_response(401)
else:
event = json.loads(body)
data = event["data"]
answer = ", " + data["answer"] if data.get("answer") else ""
print(f"Heard {event['type']} for {data['id']}: {data['state']}{answer}", flush=True)
self.send_response(200)
self.end_headers()
def log_message(self, *args):
pass
port = int(os.environ.get("PORT", "8099"))
server = HTTPServer(("127.0.0.1", port), Webhook)
print(f"Listening on http://127.0.0.1:{port}", flush=True)
server.serve_forever()Send it, and wait for your answer php/first-message.php
<?php
// Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
// PHP 8 or later, nothing to install: php first-message.php
// API_KEY and TO (your mobile number) come from the environment.
$api = getenv('API_URL') ?: 'https://api.greenmessage.app';
function call(string $method, string $url, ?array $body = null): array
{
$context = stream_context_create(['http' => [
'method' => $method,
'header' => 'Authorization: Bearer ' . getenv('API_KEY') . "\r\nContent-Type: application/json\r\n",
'content' => $body === null ? '' : json_encode($body),
'ignore_errors' => true,
]]);
return json_decode(file_get_contents($url, false, $context), true) ?? [];
}
$sent = call('POST', "$api/v1/messages", [
'recipients' => [['to' => getenv('TO')]],
'body' => 'Is this test working?',
'response' => 'confirm',
]);
$result = $sent['results'][0] ?? [];
if (($result['status'] ?? '') !== 'accepted') {
fwrite(STDERR, 'Not sent: ' . json_encode($sent) . "\n");
exit(1);
}
echo "Sent {$result['message_id']}. Answer it on your phone.\n";
$last = '';
for ($i = 0; $i < 60; $i++) {
$message = call('GET', "$api/v1/messages/{$result['message_id']}");
if ($message['state'] !== $last) {
$last = $message['state'];
echo "State: $last\n";
}
if ($last === 'answered') {
echo "Answered: {$message['answer']}\n";
exit(0);
}
if (in_array($last, ['expired', 'failed', 'cancelled'], true)) {
exit(1);
}
sleep(2);
}
fwrite(STDERR, "No answer within two minutes.\n");
exit(1);Hear the answer at your webhook php/webhook.php
<?php
// Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
// delivery. PHP 8 or later, nothing to install: php -S 127.0.0.1:8099 webhook.php
// WEBHOOK_SECRET is the secret shown when you added the endpoint. Lines go to PHP's log, here the terminal.
// signed says whether the GM-Signature header signs this raw body with your secret, within five minutes.
function signed(string $header, string $body, string $secret): bool
{
parse_str(str_replace(',', '&', $header), $parts);
$t = $parts['t'] ?? '';
if (!ctype_digit($t) || abs(time() - (int) $t) > 300 || empty($parts['v1'])) {
return false;
}
return hash_equals(hash_hmac('sha256', "$t.$body", $secret), $parts['v1']);
}
$body = file_get_contents('php://input');
if (!signed($_SERVER['HTTP_GM_SIGNATURE'] ?? '', $body, getenv('WEBHOOK_SECRET'))) {
error_log('Refused a delivery: its signature does not hold');
http_response_code(401);
return;
}
$event = json_decode($body, true);
$data = $event['data'];
$answer = empty($data['answer']) ? '' : ", {$data['answer']}";
error_log("Heard {$event['type']} for {$data['id']}: {$data['state']}$answer");Send it, and wait for your answer csharp/FirstMessage.cs
// Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
// .NET 10 or later, nothing to install: dotnet run FirstMessage.cs
// API_KEY and TO (your mobile number) come from the environment.
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
var api = Environment.GetEnvironmentVariable("API_URL") ?? "https://api.greenmessage.app";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("API_KEY"));
async Task<JsonElement> Call(HttpMethod method, string path, JsonObject? body = null)
{
using var request = new HttpRequestMessage(method, api + path);
if (body is not null) request.Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.SendAsync(request);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
}
var sent = await Call(HttpMethod.Post, "/v1/messages", new JsonObject
{
["recipients"] = new JsonArray(new JsonObject { ["to"] = Environment.GetEnvironmentVariable("TO") }),
["body"] = "Is this test working?",
["response"] = "confirm",
});
if (!sent.TryGetProperty("results", out var results) || results[0].GetProperty("status").GetString() != "accepted")
{
Console.Error.WriteLine($"Not sent: {sent}");
return 1;
}
var id = results[0].GetProperty("message_id").GetString();
Console.WriteLine($"Sent {id}. Answer it on your phone.");
var last = "";
for (var i = 0; i < 60; i++)
{
var message = await Call(HttpMethod.Get, $"/v1/messages/{id}");
var state = message.GetProperty("state").GetString();
if (state != last)
{
last = state;
Console.WriteLine($"State: {state}");
}
if (state == "answered")
{
Console.WriteLine($"Answered: {message.GetProperty("answer").GetString()}");
return 0;
}
if (state is "expired" or "failed" or "cancelled") return 1;
await Task.Delay(2000);
}
Console.Error.WriteLine("No answer within two minutes.");
return 1;Hear the answer at your webhook csharp/Webhook.cs
// Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
// delivery. .NET 10 or later, nothing to install: dotnet run Webhook.cs
// WEBHOOK_SECRET is the secret shown when you added the endpoint; PORT is where it listens.
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
var secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("WEBHOOK_SECRET") ?? "");
var port = Environment.GetEnvironmentVariable("PORT") ?? "8099";
var listener = new HttpListener();
listener.Prefixes.Add($"http://127.0.0.1:{port}/");
listener.Start();
Console.WriteLine($"Listening on http://127.0.0.1:{port}");
while (true)
{
var context = await listener.GetContextAsync();
using var buffer = new MemoryStream();
await context.Request.InputStream.CopyToAsync(buffer);
var body = buffer.ToArray();
if (!Signed(context.Request.Headers["GM-Signature"] ?? "", body))
{
Console.WriteLine("Refused a delivery: its signature does not hold");
context.Response.StatusCode = 401;
}
else
{
var root = JsonDocument.Parse(body).RootElement;
var data = root.GetProperty("data");
var answer = data.TryGetProperty("answer", out var a) && a.ValueKind == JsonValueKind.String ? $", {a.GetString()}" : "";
Console.WriteLine($"Heard {root.GetProperty("type").GetString()} for {data.GetProperty("id").GetString()}: {data.GetProperty("state").GetString()}{answer}");
context.Response.StatusCode = 200;
}
context.Response.Close();
}
// Signed says whether the GM-Signature header signs this raw body with your secret, within five minutes.
bool Signed(string header, byte[] body)
{
string? t = null, v1 = null;
foreach (var part in header.Split(','))
{
var pair = part.Split('=', 2);
if (pair.Length != 2) continue;
if (pair[0] == "t") t = pair[1];
if (pair[0] == "v1") v1 = pair[1];
}
if (t is null || v1 is null || !long.TryParse(t, out var at)
|| Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - at) > 300) return false;
byte[] payload = [.. Encoding.UTF8.GetBytes(t + "."), .. body];
var want = HMACSHA256.HashData(secret, payload);
try
{
return CryptographicOperations.FixedTimeEquals(want, Convert.FromHexString(v1));
}
catch (FormatException)
{
return false;
}
}Send it, and wait for your answer java/FirstMessage.java
// Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
// Java 17 or later, nothing to install: java FirstMessage.java
// API_KEY and TO (your mobile number) come from the environment. It reads the few fields it needs with a
// pattern; your own code would use its JSON library.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Pattern;
public class FirstMessage {
static final String API = System.getenv().getOrDefault("API_URL", "https://api.greenmessage.app");
static final HttpClient HTTP = HttpClient.newHttpClient();
static String call(String method, String path, String body) throws Exception {
var request = HttpRequest.newBuilder(URI.create(API + path))
.header("Authorization", "Bearer " + System.getenv("API_KEY"))
.header("Content-Type", "application/json")
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body))
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString()).body();
}
static String field(String json, String name) {
var match = Pattern.compile("\"" + name + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
return match.find() ? match.group(1) : "";
}
public static void main(String[] args) throws Exception {
var sent = call("POST", "/v1/messages", "{\"recipients\":[{\"to\":\"" + System.getenv("TO")
+ "\"}],\"body\":\"Is this test working?\",\"response\":\"confirm\"}");
if (!field(sent, "status").equals("accepted")) {
System.err.println("Not sent: " + sent);
System.exit(1);
}
var id = field(sent, "message_id");
System.out.println("Sent " + id + ". Answer it on your phone.");
var last = "";
for (int i = 0; i < 60; i++) {
var message = call("GET", "/v1/messages/" + id, null);
var state = field(message, "state");
if (!state.equals(last)) {
last = state;
System.out.println("State: " + state);
}
if (state.equals("answered")) {
System.out.println("Answered: " + field(message, "answer"));
System.exit(0);
}
if (state.equals("expired") || state.equals("failed") || state.equals("cancelled")) {
System.exit(1);
}
Thread.sleep(2000);
}
System.err.println("No answer within two minutes.");
System.exit(1);
}
}Hear the answer at your webhook java/Webhook.java
// Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
// delivery. Java 17 or later, nothing to install: java Webhook.java
// WEBHOOK_SECRET is the secret shown when you added the endpoint; PORT is where it listens. It reads the few
// fields it needs with a pattern; your own code would use its JSON library.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Webhook {
static final byte[] SECRET = System.getenv().getOrDefault("WEBHOOK_SECRET", "").getBytes(StandardCharsets.UTF_8);
// signed says whether the GM-Signature header signs this raw body with your secret, within five minutes.
static boolean signed(String header, byte[] body) {
String t = null, v1 = null;
for (var part : header.split(",")) {
var pair = part.split("=", 2);
if (pair.length == 2 && pair[0].equals("t")) t = pair[1];
if (pair.length == 2 && pair[0].equals("v1")) v1 = pair[1];
}
if (t == null || v1 == null || !t.matches("\\d{1,12}")
|| Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(t)) > 300) return false;
try {
var mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET, "HmacSHA256"));
mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
return MessageDigest.isEqual(mac.doFinal(body), HexFormat.of().parseHex(v1));
} catch (GeneralSecurityException | IllegalArgumentException e) {
return false;
}
}
static String field(String json, String pattern) {
var match = Pattern.compile(pattern).matcher(json);
return match.find() ? match.group(1) : "";
}
public static void main(String[] args) throws Exception {
var port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8099"));
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
server.createContext("/", exchange -> {
try {
var body = exchange.getRequestBody().readAllBytes();
var header = exchange.getRequestHeaders().getFirst("GM-Signature");
if (!signed(header == null ? "" : header, body)) {
System.out.println("Refused a delivery: its signature does not hold");
exchange.sendResponseHeaders(401, -1);
return;
}
var json = new String(body, StandardCharsets.UTF_8);
var answer = field(json, "\"answer\"\\s*:\\s*\"([^\"]*)\"");
System.out.println("Heard " + field(json, "\"type\"\\s*:\\s*\"([^\"]*)\"")
+ " for " + field(json, "\"id\"\\s*:\\s*\"(msg_[^\"]*)\"")
+ ": " + field(json, "\"state\"\\s*:\\s*\"([^\"]*)\"")
+ (answer.isEmpty() ? "" : ", " + answer));
exchange.sendResponseHeaders(200, -1);
} finally {
exchange.close();
}
});
server.start();
System.out.println("Listening on http://127.0.0.1:" + port);
}
}Send it, and wait for your answer go/first-message/main.go
// Send "Is this test working?", with Yes and No, to your own phone, then wait for your answer.
// Go 1.21 or later, nothing to install: go run main.go
// API_KEY and TO (your mobile number) come from the environment.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
func main() {
api := os.Getenv("API_URL")
if api == "" {
api = "https://api.greenmessage.app"
}
call := func(method, path string, body any) map[string]any {
var payload []byte
if body != nil {
payload, _ = json.Marshal(body)
}
req, _ := http.NewRequest(method, api+path, bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+os.Getenv("API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer res.Body.Close()
out := map[string]any{}
json.NewDecoder(res.Body).Decode(&out)
return out
}
sent := call("POST", "/v1/messages", map[string]any{
"recipients": []map[string]string{{"to": os.Getenv("TO")}},
"body": "Is this test working?",
"response": "confirm",
})
results, _ := sent["results"].([]any)
if len(results) == 0 || results[0].(map[string]any)["status"] != "accepted" {
raw, _ := json.Marshal(sent)
fmt.Fprintln(os.Stderr, "Not sent:", string(raw))
os.Exit(1)
}
id := results[0].(map[string]any)["message_id"].(string)
fmt.Printf("Sent %s. Answer it on your phone.\n", id)
last := ""
for i := 0; i < 60; i++ {
message := call("GET", "/v1/messages/"+id, nil)
state, _ := message["state"].(string)
if state != last {
last = state
fmt.Println("State:", state)
}
switch state {
case "answered":
fmt.Println("Answered:", message["answer"])
return
case "expired", "failed", "cancelled":
os.Exit(1)
}
time.Sleep(2 * time.Second)
}
fmt.Fprintln(os.Stderr, "No answer within two minutes.")
os.Exit(1)
}Hear the answer at your webhook go/webhook/main.go
// Hear each answer as it happens: the endpoint your server runs, checking GreenMessage's signature on every
// delivery. Go 1.22 or later, nothing to install: go run main.go
// WEBHOOK_SECRET is the secret shown when you added the endpoint; PORT is where it listens.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
// signed says whether the GM-Signature header signs this raw body with your secret, within five minutes.
func signed(secret, header string, body []byte) bool {
var t, v1 string
for _, part := range strings.Split(header, ",") {
if k, v, ok := strings.Cut(part, "="); ok {
switch k {
case "t":
t = v
case "v1":
v1 = v
}
}
}
at, err := strconv.ParseInt(t, 10, 64)
if err != nil || time.Since(time.Unix(at, 0)).Abs() > 5*time.Minute {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(t + "."))
mac.Write(body)
want, err := hex.DecodeString(v1)
return err == nil && hmac.Equal(mac.Sum(nil), want)
}
func main() {
secret := os.Getenv("WEBHOOK_SECRET")
port := os.Getenv("PORT")
if port == "" {
port = "8099"
}
http.HandleFunc("POST /", func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
if !signed(secret, r.Header.Get("GM-Signature"), body) {
fmt.Println("Refused a delivery: its signature does not hold")
w.WriteHeader(http.StatusUnauthorized)
return
}
var event struct {
Type string `json:"type"`
Data struct {
ID string `json:"id"`
State string `json:"state"`
Answer string `json:"answer"`
} `json:"data"`
}
json.Unmarshal(body, &event)
answer := ""
if event.Data.Answer != "" {
answer = ", " + event.Data.Answer
}
fmt.Printf("Heard %s for %s: %s%s\n", event.Type, event.Data.ID, event.Data.State, answer)
})
fmt.Println("Listening on http://127.0.0.1:" + port)
if err := http.ListenAndServe("127.0.0.1:"+port, nil); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
} Not sent? The answer says why. example_number: the number is one kept for films and books, such as 07700 900123, so send to your own. not_a_test_number: a test key reaches only your test numbers.
Built for production
The parts you would otherwise have to build.
Idempotency-Key again and you get the first answer, not a second message.