PayRamHost hosted onboarding is paused · Guides keep updatingGet notified when it reopens →

Docs / Go example

PayRam webhook signature verification in Go (net/http)

The standard library is all you need: read the raw bytes, verify, and only then parse the JSON.

Last updated · By the PayRamHost editors · Markdown version

PayRamHost hosted merchant onboarding has been paused since 29 November 2026. Where this guide mentions PayRamHost, it describes the situation before the pause; the PayRam usage it explains still applies.

The short version: a PayRam webhook signature is an HMAC-SHA256 of the raw request body, keyed with your project API key, sent in the header X-Payram-Signature: sha256=<hex>. In Go the key is to get the raw bytes untouched by the framework and compute the signature over them. Below is a complete, tested version.

1. Before you start

  • Go 1.20 or later (this guide uses only the standard library).
  • Put the project API key in the environment variable PAYRAM_API_KEY.
  • Register an HTTPS callback address for the project in the PayRam dashboard and set it to active; see the webhook guide.
  • With several projects, verify each with its own API key; see multiple projects.

2. The complete code

File: main.go

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
)

// 项目 API 密钥,只放在环境变量里
var apiKey = []byte(os.Getenv("PAYRAM_API_KEY"))

type event struct {
	ReferenceID string `json:"reference_id"`
	InvoiceID   string `json:"invoice_id"`
	Status      string `json:"status"`
}

func isValid(raw []byte, header string) bool {
	mac := hmac.New(sha256.New, apiKey)
	mac.Write(raw)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(header), []byte(expected)) // 恒定时间比较
}

func webhook(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// 先把原始字节读出来,再验签,最后才解析 JSON;限制大小,防止被塞超大请求
	raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if !isValid(raw, r.Header.Get("X-Payram-Signature")) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	var e event
	if err := json.Unmarshal(raw, &e); err != nil {
		http.Error(w, "bad json", http.StatusBadRequest)
		return
	}

	// 以 ReferenceID + Status 做幂等:同一条通知可能重复到达。
	// 尽快返回 2xx,耗时的事交给 goroutine 或任务队列。
	go handleEvent(e)

	w.WriteHeader(http.StatusOK)
}

func handleEvent(e event) {
	// TODO:查你自己的订单(InvoiceID),状态是 FILLED 或 OVER_FILLED 才发货
}

func main() {
	http.HandleFunc("/payram/webhook", webhook)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

The code in this guide was tested locally before publishing: test cases cover a valid signature, a tampered body, re-serialised JSON, a missing signature, a short signature, a wrong key and more, and we confirmed that the openssl command below produces the same signature as the code.

3. Setup and routing

Save as main.go and run it. The callback address is https://your-domain/payram/webhook (usually behind nginx or Caddy):

PAYRAM_API_KEY=your-project-api-key go run .

4. Why it is written this way

  • io.ReadAll first, verify next, json.Unmarshal last. Do not stream-decode with json.NewDecoder(r.Body), or you never get the raw bytes.
  • Compare in constant time with hmac.Equal. Never compare signatures with ==.
  • Limit the body size with http.MaxBytesReader. The callback address is public, and a limit stops people from sending huge requests.
  • Header case does not matter. r.Header.Get("X-Payram-Signature") handles canonicalisation.
  • Return 2xx first, then process in a goroutine. In production prefer a task queue over spawning unlimited goroutines.

5. Testing locally

The command below computes the correct signature with your key and sends a simulated callback to your local server. It should return 200; change any one character in BODY and send it again, and it should return 401. Use the key of a separate test project, not a production one.

export PAYRAM_API_KEY='your test project API key'
BODY='{"reference_id":"a1b2c3d4e5","invoice_id":"INV-0090","status":"FILLED"}'
SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$PAYRAM_API_KEY" -hex | sed 's/^.* //')"
curl -i -X POST http://localhost:8080/payram/webhook \
  -H "Content-Type: application/json" \
  -H "X-Payram-Signature: $SIG" \
  -d "$BODY"

6. What to add before going live

  • Idempotency. The same notification can arrive twice. Use reference_id plus status as a unique key and answer 200 straight away if it was already handled.
  • Ship only after receipt. Ship only on FILLED or OVER_FILLED; see payment statuses.
  • Return 2xx first, then process. PayRam retries requests answered with 400 or above, or with no response within 60 seconds; the rules are in the webhook guide.
  • Use the status endpoint as a safety net. If a notification is ever missed, reconcile with the status endpoint.
  • Run it once with a real 1 US dollar payment. See the go-live checklist.

7. FAQ

How do I unit test it?

Use net/http/httptest: build a request, set X-Payram-Signature, call webhook(rec, req) and check rec.Code. Our tests cover a valid signature, a tampered body, re-serialised JSON, a missing signature, a short signature, a wrong key and a non-POST request.

What about Gin, Echo or Fiber?

The principle is the same: get the raw bytes before the framework parses the body (c.GetRawData() in Gin; Echo and Fiber have their own readers) and verify with the same isValid function. We did not test each of these frameworks.

Why do I get 401?

The most common cause is using the wrong project’s API key, or a proxy that rewrites the body on the way.

  • Webhook guide: How to receive PayRam webhooks: register an endpoint, verify X-Payram-Signature, understand retry rules and payment states, handle duplicates, with Node.js and Python examples.
  • Payment statuses: What PayRam's five payment statuses mean, how to handle underpaid (PARTIALLY_FILLED), overpaid (OVER_FILLED) and expired (CANCELLED) payments, and how to keep your order status in sync using webhooks and the status endpoint.
  • Create payments via API: Add crypto payments to your own site with the PayRam API: create a payment and get a payment link, send the customer to the payment page, confirm receipt with webhooks and the status endpoint, and reconcile by order number. With curl, Node.js and Python examples.
  • Go-live checklist: PayRam mainnet has no sandbox, so test with small real amounts before launch. This checklist covers, in order: checking the configuration, one payment per chain and coin, verifying sweeping, under- and overpayment and expiry, webhooks, refunds and payouts, the card channel, and where to look when something fails.

Sources

This guide is based on the PayRam official documentation below, checked on 2026-11-12. PayRamHost is an independently operated service and is not affiliated with PayRam. If anything differs, the official documentation prevails.