# How to handle the result (https://developer.godaddy.com/en/docs/api-users/commerce/accept-payments/in-person-payments/handle-result)

---
title: How to handle the result
description: >-
  Receive and verify HMAC-signed payment request callbacks, and list payment
  requests to find results your server missed.
keywords: >-
  handle payment result, payment request callback, callbackConfig, HMAC,
  X-Signature, X-Timestamp, X-Request-Id, includeFields, legacyMode, list
  payment requests, reconcile payment requests, commerce.payment-request:read.
agentNotes:
  permissions:
    - GoDaddy Payments
  scopes:
    - 'commerce.payment-request:read'
  idempotent: true
  destructive: false
  failureRecovery: >-
    Reject a callback whose X-Timestamp is outside your replay window or whose
    X-Signature doesn't match the HMAC of the raw body, X-Timestamp, and
    X-Request-Id. GoDaddy sends one callback per payment request and doesn't
    filter by events; this might change. Every callback body carries status,
    whatever includeFields lists. Return 2XX within 5 seconds to acknowledge a
    callback; a 4XX ends delivery, and a 5XX or timeout gets retried for about
    51 minutes. Every callback has a new X-Request-Id, so detect duplicates by
    paymentRequestId and status. The list call is safe to retry; without
    updatedAtAfter it covers the last day. A 401 means the token is missing,
    expired, or invalid; confirm it has commerce.payment-request:read. That 401
    might have an empty body.
related:
  guides:
    - title: How to charge a card on a terminal
      href: >-
        /docs/api-users/commerce/accept-payments/in-person-payments/charge-a-card
    - title: How to connect your terminal
      href: >-
        /docs/api-users/commerce/accept-payments/in-person-payments/connect-terminal
  concepts:
    - title: About Payment Requests
      href: /docs/api-users/commerce/accept-payments/in-person-payments
    - title: Payment request reference
      href: /docs/api-users/commerce/accept-payments/in-person-payments/reference
  apis:
    - title: Get all payment requests
      href: /docs/references/rest/payments/get-payment-requests
    - title: Get a payment request by ID
      href: /docs/references/rest/payments/get-payment-request-by-id
pageId: 91cc53d0-9155-4926-aa66-c963fe442485
---

## Overview

This page covers how GoDaddy pushes payment request status updates to your server, and how to find results your server missed. GoDaddy sends a callback to the `callbackConfig.url` you set on create. `GET /v1/commerce/stores/{storeId}/payment-requests` on the Payment Requests API lists a store's payment requests, so you can reconcile after your endpoint was down. Go to [How to charge a card on a terminal](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/charge-a-card) to get one payment request by ID instead.

Callbacks with `authentication.type` set to `hmac` carry an `X-Signature` header: the hex-encoded HMAC-SHA256 of the raw body concatenated with the `X-Timestamp` and `X-Request-Id` values, keyed with your secret. `X-Timestamp` is in epoch seconds. GoDaddy signs each scheduled retry again with the current time and a new `X-Request-Id`, so a 300-second replay window covers the whole retry schedule. The `X-Request-Id` isn't the one you sent on create.

Your endpoint returns `401` for a callback whose `X-Timestamp` is outside your replay window, or whose signature doesn't match. Inside the window, a copied callback still verifies, so the duplicate check on `paymentRequestId` and `status` keeps it from updating an order twice.

The handlers on this page listen on `http://localhost:3000/webhooks/payment-requests` and use a 300-second window. The Python handler needs Flask, and the Python list example needs `requests`. The curl tab doesn't verify anything. It signs and sends a test callback to that local URL, so you can check your handler before GoDaddy calls it. Go to [Payment request reference](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/reference) for callback fields, statuses, list filters, and error codes.

## Prerequisites

The following prerequisites are required before you can handle the result:

* the `paymentRequestId` of a request from [How to charge a card on a terminal](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/charge-a-card)
* a [Personal Access Token (PAT)](https://developer.godaddy.com/docs/api-users/auth/how-to) with the `commerce.payment-request:read` scope for listing and reading status
* a public HTTPS endpoint and the shared secret you sent in `callbackConfig.authentication.value`, when you use callbacks

## Configure the callback

Send `callbackConfig` in the create body with your `url`, at least one field in `payloadConfig.includeFields`, and `authentication.type` set to `hmac`. Use `none` during development only. Don't log create requests or responses, because they carry your callback credentials.

GoDaddy sends one callback per payment request, after the terminal reports the result. Read `status` from that callback instead of assuming the payment succeeded. Return `2XX` within 5 seconds to acknowledge it. Return `5XX` for a temporary failure on your side, so GoDaddy retries instead of dropping the callback. The same callback can reach you more than once.

Go to [Payment request reference](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/reference#callbacks) for every `callbackConfig` field, the `includeFields` values, the authentication types, and the retry schedule.

## Verify the callback signature

The following procedure verifies a callback signature.

1. Read the raw request body before any JSON parsing.

2. Check that `X-Timestamp` is inside your replay window.

3. Compute `hex(HMAC-SHA256(secret, rawBody + X-Timestamp + X-Request-Id))` from the headers on the callback.

4. Compare the result with `X-Signature` in constant time:

   ```bash tab="curl"
   # Sign a sample body the way GoDaddy does, then send it to your local handler.
   BODY='{"paymentRequestId":"'"$PAYMENT_REQUEST_ID"'","type":"SALE","status":"COMPLETED"}'
   TIMESTAMP=$(date +%s)
   REQUEST_ID=$(uuidgen)
   SIGNATURE=$(printf '%s%s%s' "$BODY" "$TIMESTAMP" "$REQUEST_ID" \
     | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $NF}')

   curl -sS -w "\n%{http_code}\n" -X POST "http://localhost:3000/webhooks/payment-requests" \
     -H "Content-Type: application/json" \
     -H "X-Signature: $SIGNATURE" \
     -H "X-Timestamp: $TIMESTAMP" \
     -H "X-Request-Id: $REQUEST_ID" \
     -d "$BODY"
   ```

   ```js tab="Node"
   import { createHmac, timingSafeEqual } from "node:crypto";
   import { createServer } from "node:http";

   const secret = process.env.WEBHOOK_SECRET;
   if (!secret) {
     throw new Error("Set WEBHOOK_SECRET");
   }
   const maxAgeSeconds = 300;

   createServer((req, res) => {
     if (req.method !== "POST" || req.url !== "/webhooks/payment-requests") {
       res.writeHead(404).end();
       return;
     }

     const chunks = [];
     req.on("data", (chunk) => chunks.push(chunk));
     req.on("end", () => {
       const rawBody = Buffer.concat(chunks);
       const timestamp = String(req.headers["x-timestamp"] ?? "");
       const requestId = String(req.headers["x-request-id"] ?? "");
       const signature = Buffer.from(
         String(req.headers["x-signature"] ?? "").toLowerCase()
       );

       const age = Math.floor(Date.now() / 1000) - Number(timestamp);
       if (!/^\d+$/.test(timestamp) || Math.abs(age) > maxAgeSeconds) {
         res.writeHead(401).end();
         return;
       }

       const expected = Buffer.from(
         createHmac("sha256", secret)
           .update(rawBody)
           .update(`${timestamp}${requestId}`)
           .digest("hex")
       );

       if (
         signature.length !== expected.length ||
         !timingSafeEqual(signature, expected)
       ) {
         res.writeHead(401).end();
         return;
       }

       res.writeHead(200).end();

       try {
         const payload = JSON.parse(rawBody.toString("utf8"));
         console.log(payload.paymentRequestId, payload.status, requestId);
       } catch (err) {
         console.error("Unreadable callback body", err);
       }
     });
   }).listen(3000);
   ```

   ```python tab="Python"
   import hashlib, hmac, json, os, time
   from flask import Flask, request

   app = Flask(__name__)
   secret = os.environ["WEBHOOK_SECRET"].encode()
   MAX_AGE_SECONDS = 300

   @app.post("/webhooks/payment-requests")
   def payment_request_callback():
       raw_body = request.get_data()
       timestamp = request.headers.get("X-Timestamp", "")
       request_id = request.headers.get("X-Request-Id", "")
       signature = request.headers.get("X-Signature", "").lower()

       if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > MAX_AGE_SECONDS:
           return "", 401

       expected = hmac.new(
           secret, raw_body + (timestamp + request_id).encode(), hashlib.sha256
       ).hexdigest()

       if not hmac.compare_digest(signature.encode(), expected.encode()):
           return "", 401

       try:
           payload = json.loads(raw_body)
           print(payload.get("paymentRequestId"), payload.get("status"), request_id)
       except ValueError:
           print("Unreadable callback body")
       return "", 200

   if __name__ == "__main__":
       app.run(port=3000)
   ```

   ```go tab="Go"
   package main

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

   const maxAgeSeconds = 300

   func main() {
   	secret := []byte(os.Getenv("WEBHOOK_SECRET"))
   	if len(secret) == 0 {
   		log.Fatal("Set WEBHOOK_SECRET")
   	}

   	http.HandleFunc("/webhooks/payment-requests", func(w http.ResponseWriter, r *http.Request) {
   		if r.Method != http.MethodPost {
   			w.WriteHeader(http.StatusMethodNotAllowed)
   			return
   		}
   		rawBody, err := io.ReadAll(r.Body)
   		if err != nil {
   			w.WriteHeader(http.StatusBadRequest)
   			return
   		}
   		timestamp := r.Header.Get("X-Timestamp")
   		requestID := r.Header.Get("X-Request-Id")
   		signature := strings.ToLower(r.Header.Get("X-Signature"))

   		sent, err := strconv.ParseInt(timestamp, 10, 64)
   		age := time.Now().Unix() - sent
   		if err != nil || age > maxAgeSeconds || age < -maxAgeSeconds {
   			w.WriteHeader(http.StatusUnauthorized)
   			return
   		}

   		mac := hmac.New(sha256.New, secret)
   		mac.Write(rawBody)
   		mac.Write([]byte(timestamp + requestID))
   		expected := hex.EncodeToString(mac.Sum(nil))

   		if !hmac.Equal([]byte(signature), []byte(expected)) {
   			w.WriteHeader(http.StatusUnauthorized)
   			return
   		}

   		w.WriteHeader(http.StatusOK)

   		var payload map[string]any
   		if err := json.Unmarshal(rawBody, &payload); err != nil {
   			log.Println("Unreadable callback body:", err)
   			return
   		}
   		fmt.Println(payload["paymentRequestId"], payload["status"], requestID)
   	})

   	log.Fatal(http.ListenAndServe(":3000", nil))
   }
   ```

5. Respond to the callback before you do slow work.

6. Read `status` from the verified callback body.

7. Drop a callback whose `paymentRequestId` and `status` you already processed.

## List payment requests

`GET /v1/commerce/stores/{storeId}/payment-requests` returns a store's payment requests, newest update first. Without `updatedAtAfter`, the list covers the last day. Pass the response's `pageToken`, with the same filters, to get the next page.

The following procedure lists every payment request updated since `UPDATED_AT_AFTER`, like the start of an outage.

* List the payment requests, one page at a time:

  ```bash tab="curl"
  PAGE_TOKEN=""
  while :; do
    page=$(curl -sS -f -G "https://api.godaddy.com/v1/commerce/stores/$STORE_ID/payment-requests" \
      -H "Authorization: Bearer $GODADDY_PAT" \
      --data-urlencode "updatedAtAfter=$UPDATED_AT_AFTER" \
      --data-urlencode "pageSize=100" \
      ${PAGE_TOKEN:+--data-urlencode "pageToken=$PAGE_TOKEN"}) || { echo "request failed" >&2; break; }
    jq -r '.items[]? | "\(.paymentRequestId) \(.status)"' <<< "$page"
    PAGE_TOKEN=$(jq -r '.pageToken // empty' <<< "$page")
    [ -n "$PAGE_TOKEN" ] || break
  done
  ```

  ```js tab="Node"
  const token = process.env.GODADDY_PAT;
  const storeId = process.env.STORE_ID;

  let pageToken;
  do {
    const params = new URLSearchParams({
      updatedAtAfter: process.env.UPDATED_AT_AFTER,
      pageSize: "100",
    });
    if (pageToken) {
      params.set("pageToken", pageToken);
    }
    const res = await fetch(
      `https://api.godaddy.com/v1/commerce/stores/${storeId}/payment-requests?${params}`,
      { headers: { Authorization: `Bearer ${token}` } }
    );
    if (!res.ok) {
      throw new Error(`${res.status} ${await res.text()}`);
    }
    const page = await res.json();
    for (const item of page.items ?? []) {
      console.log(item.paymentRequestId, item.status);
    }
    pageToken = page.pageToken;
  } while (pageToken);
  ```

  ```python tab="Python"
  import os, requests

  token = os.environ["GODADDY_PAT"]
  store_id = os.environ["STORE_ID"]
  params = {"updatedAtAfter": os.environ["UPDATED_AT_AFTER"], "pageSize": 100}

  while True:
      res = requests.get(
          f"https://api.godaddy.com/v1/commerce/stores/{store_id}/payment-requests",
          params=params,
          headers={"Authorization": f"Bearer {token}"},
      )
      res.raise_for_status()
      page = res.json()
      for item in page.get("items", []):
          print(item["paymentRequestId"], item["status"])
      if not page.get("pageToken"):
          break
      params["pageToken"] = page["pageToken"]
  ```

  ```go tab="Go"
  package main

  import (
  	"encoding/json"
  	"fmt"
  	"io"
  	"net/http"
  	"net/url"
  	"os"
  )

  type paymentRequestPage struct {
  	Items []struct {
  		PaymentRequestID string `json:"paymentRequestId"`
  		Status           string `json:"status"`
  	} `json:"items"`
  	PageToken string `json:"pageToken"`
  }

  func main() {
  	token := os.Getenv("GODADDY_PAT")
  	storeId := os.Getenv("STORE_ID")

  	params := url.Values{}
  	params.Set("updatedAtAfter", os.Getenv("UPDATED_AT_AFTER"))
  	params.Set("pageSize", "100")

  	for {
  		endpoint := fmt.Sprintf(
  			"https://api.godaddy.com/v1/commerce/stores/%s/payment-requests?%s",
  			storeId,
  			params.Encode(),
  		)
  		req, err := http.NewRequest("GET", endpoint, nil)
  		if err != nil {
  			panic(err)
  		}
  		req.Header.Set("Authorization", "Bearer "+token)

  		res, err := http.DefaultClient.Do(req)
  		if err != nil {
  			panic(err)
  		}
  		body, err := io.ReadAll(res.Body)
  		res.Body.Close()
  		if err != nil {
  			panic(err)
  		}
  		if res.StatusCode != http.StatusOK {
  			panic(fmt.Sprintf("%d %s", res.StatusCode, body))
  		}

  		var page paymentRequestPage
  		if err := json.Unmarshal(body, &page); err != nil {
  			panic(err)
  		}
  		for _, item := range page.Items {
  			fmt.Println(item.PaymentRequestID, item.Status)
  		}
  		if page.PageToken == "" {
  			break
  		}
  		params.Set("pageToken", page.PageToken)
  	}
  }
  ```

Add `status`, `deviceId`, or `type` to the query to narrow the list, like `status=FAILED` for failed requests only.

## Example responses

### Callback

The following table lists the headers on an `hmac` callback:

| Header         | Value                                                  |
| -------------- | ------------------------------------------------------ |
| `Content-Type` | `application/json`                                     |
| `X-Signature`  | The hex-encoded HMAC-SHA256 signature                  |
| `X-Timestamp`  | The time GoDaddy signed this attempt, in epoch seconds |
| `X-Request-Id` | A new UUID for this attempt                            |

GoDaddy sends the body as compact JSON, and field order can vary, so verify the raw bytes. The following body is for the `includeFields` in [Add an order reference and a callback](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/charge-a-card#add-an-order-reference-and-a-callback), formatted for reading:

```json
{
  "paymentRequestId": "$PAYMENT_REQUEST_ID",
  "type": "SALE",
  "status": "COMPLETED",
  "amount": { "amount": 5000, "currency": "USD", "amountType": "SIMPLE" },
  "transactionIds": ["$TRANSACTION_ID"]
}
```

### List response

A response with `pageToken` has more results. The last page has no `pageToken`. `pageToken` is an opaque string, so pass it back unchanged. The following example is a page with more results:

```json
{
  "items": [
    {
      "paymentRequestId": "$PAYMENT_REQUEST_ID",
      "type": "SALE",
      "status": "COMPLETED",
      "amount": { "amount": 5000, "currency": "USD", "amountType": "SIMPLE" }
    }
  ],
  "pageToken": "$PAGE_TOKEN"
}
```

## Common errors

The following table lists common situations when you handle the result and what to do:

| Situation                                | Most likely cause                                                                                                     | What to do                                                   |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| No callback arrives                      | The request failed at create, delivery is still retrying, your endpoint returned `4XX`, or the URL isn't public HTTPS | Get the payment request, then check `callbackConfig.url`     |
| Every callback fails verification        | The wrong secret, or a body your framework parsed before you signed it                                                | Sign the raw bytes with the secret you sent on create        |
| Your handler rejects every `X-Timestamp` | Your server clock is more than 300 seconds off, and each `401` ends delivery                                          | Sync your server clock with NTP                              |
| The same callback arrives twice          | GoDaddy retried delivery                                                                                              | Drop a `paymentRequestId` and `status` you already processed |
| The list misses an older request         | `updatedAtAfter` defaults to 1 day ago                                                                                | Set `updatedAtAfter` to an earlier RFC 3339 date-time        |
| List returns `400`                       | An invalid filter value                                                                                               | Check `updatedAtAfter`, `updatedAtBefore`, and `status`      |
| List returns `401`                       | A missing, expired, or invalid PAT, or a missing scope                                                                | Create a token with `commerce.payment-request:read`          |

Go to [Payment request reference](https://developer.godaddy.com/docs/api-users/commerce/accept-payments/in-person-payments/reference#status-codes) for every status code and the error body.
