Ambito API

Riferimento API per sviluppatori

Esempi cURL e Node focalizzati sulla produzione per checkout con stablecoin, creazione di ordini e tracciamento delle consegne.

Coperto in questa guida

  • Gift card
  • Ricariche mobili
  • Acquisti di eSIM

Non coperto qui

  • Voli
  • Soggiorni

Hai bisogno del contesto di integrazione più ampio prima di immergerti negli endpoint?

Apri panoramica dell'integrazione
1

Autenticazione

Ogni richiesta API richiede queste intestazioni. Dopo aver creato un account Cryptorefills, puoi trovare il tuo ID partner nella pagina delle informazioni del tuo account.
bash
# Required headers for every API request
-H 'X-Cr-Application: YOUR_PARTNER_ID'
-H 'X-Cr-Version: YOUR_APP_VERSION'
-H 'X-Country-ISO-Code: US'
-H 'Content-Type: application/json'
2

Metodi di pagamento

GET/v3/payment_vias
Recupera tutte le monete e le reti blockchain supportate. Restituisce USDC, USDT su Solana, Ethereum, Base, Arbitrum, Polygon e altro.
bash
curl -X GET 'https://api.cryptorefills.com/v3/payment_vias' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'

Consigliato: USDC su Solana offre le commissioni più basse e il regolamento più veloce.

3

Catalogo marchi

GET/v2/brands?country_code={countryCode}
(Opzionale) Elenca tutti i marchi disponibili per un paese. Ottimo per costruire un directory di marchi o funzionalità di ricerca.
bash
curl -X GET 'https://api.cryptorefills.com/v2/brands?country_code=US' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'
4

Feed della homepage

GET/v2/homepage?country_code={countryCode}
(Opzionale) Recupera un feed curato per la homepage di un paese. Utile per visualizzare carte regalo in tendenza o in evidenza.
bash
curl -X GET 'https://api.cryptorefills.com/v2/homepage?country_code=US' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'
5

Sfoglia i prodotti

GET/v5/products/country/{countryCode}
Elenca tutte le carte regalo disponibili per un marchio e un paese. Supporta denominazioni fisse e importi personalizzati (intervalli).
bash
curl -X GET 'https://api.cryptorefills.com/v5/products/country/US?family_name=airbnb&coin=USDC&lang=en' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'
6

Ottieni il prezzo delle criptovalute

GET/v4/products/price
Converti qualsiasi valore di carta regalo in un importo di stablecoin. Usa questo per mostrare agli utenti l'importo esatto in criptovaluta prima di confermare l'acquisto.
bash
curl -X GET 'https://api.cryptorefills.com/v4/products/price?brand_name=Airbnb&country_code=US&face_value=100&coin=USDC' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'
7

Convalida ordine

POST/v5/orders/validations
(Consigliato) Controlla eventuali problemi prima di creare l'ordine. Usa l'email reale dell'utente finale in email/beneficiary_account, poiché Cryptorefills consegna a quel destinatario.
bash
curl -X POST 'https://api.cryptorefills.com/v5/orders/validations' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION' \
  -d '{
    "email": "END_USER_EMAIL",
    "payment": {
      "type": "via",
      "payment_via": "USER_WALLET",
      "coin": "USDC"
    },
    "deliveries": [
      {
        "beneficiary_account": "END_USER_EMAIL",
        "brand_name": "Airbnb",
        "country_code": "US",
        "denomination": "100 USD",
        "localized_denomination": "$100"
      }
    ],
    "lang": "en"
  }'
8

Crea ordine

POST/v5/orders
Crea un ordine e ricevi un indirizzo wallet per il pagamento. Usa l'email reale dell'utente finale perché Cryptorefills deve consegnare il prodotto a quel destinatario. La finestra di pagamento è di 30 minuti.
bash
curl -X POST 'https://api.cryptorefills.com/v5/orders' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION' \
  -d '{
    "deliveries": [
      {
        "kind": "giftcard",
        "quantity": 1,
        "deliverable": {
          "brand_name": "Airbnb",
          "country_code": "US",
          "denomination": "100"
        }
      }
    ],
    "payment": {
      "type": "via",
      "coin": "USDC",
      "network": "Solana",
      "payment_via": "USER_WALLET"
    },
    "user": {
      "email": "END_USER_EMAIL",
      "has_accepted_newsletter": true
    },
    "lang": "en",
    "acquisition": {
      "utm_source": "your_platform"
    }
  }'

La risposta include wallet_address and coin_amount. Condividi questi con il tuo utente.

9a

Traccia ordine (stream API)

GET/api/orders/{orderId}/subscribe
Implementa questo in due parti richieste: un percorso proxy SSE lato server e un hook stream lato client.
  • Il percorso API riceve/api/orders/{orderId}/subscribe e inoltra a upstream/v5/orders/{orderId}/subscribe.
  • L'hook client apreEventSource al percorso API locale, convalida i payload e si riconnette con backoff quando necessario.

Codice essenziale lato server

javascript
// app/api/orders/[orderId]/subscribe/route.ts
let upstream: Response;

try {
  upstream = await fetch(
    `https://api.cryptorefills.com/v5/orders/${params?.orderId}/subscribe`,
    {
      method: 'GET',
      headers: {
        ...(await genHeader.server(session)),
        'User-Agent': user_agent,
        Accept: 'text/event-stream',
        Connection: 'keep-alive',
      },
    },
  );
} catch (err) {
  return NextResponse.json(
    { error: 'Failed to connect to upstream stream' },
    { status: 502 },
  );
}

if (!upstream.ok || !upstream.body) {
  return NextResponse.json(
    { error: 'Upstream returned an error' },
    { status: upstream.status || 502 },
  );
}

// stream = ReadableStream that proxies upstream SSE events
return new Response(stream, {
  status: 200,
  headers: {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache, no-transform',
    Connection: 'keep-alive',
    'X-Accel-Buffering': 'no',
  },
});

Codice essenziale lato client

javascript

const { data: lastEvent, error } = useSWRSubscription<TOrderSchema>(
  referenceOrderId ? `orders-info-stream-${referenceOrderId}` : null,
  ((key, { next }) => {
    let es: EventSource | null = null;
    let stopped = false;
    let shouldReconnect = true;
    let retryTimeout: number | null = null;
    let retryDelay = 1000;

    const cleanup = () => {
      if (es) {
        es.close();
        es = null;
      }
      if (retryTimeout !== null) {
        window.clearTimeout(retryTimeout);
        retryTimeout = null;
      }
    };

    const stopForever = () => {
      shouldReconnect = false;
      stopped = true;
      cleanup();
    };

    const connect = () => {
      if (stopped) return;
      cleanup();
      es = new EventSource(`/api/orders/${referenceOrderId}/subscribe`);

      es.addEventListener('message', (ev) => {
        try {
          const raw = JSON.parse(ev.data);
          const parsed = orderSchema.safeParse(raw);
          if (!parsed.success) return;
          retryDelay = 1000;
          next(null, parsed.data as TOrderSchema);
        } catch (err) {
          next(err as Error);
        }
      });

      es.addEventListener('stop', () => {
        stopForever();
      });

      es.onerror = () => {
        if (stopped || !shouldReconnect) return;
        cleanup();
        retryTimeout = window.setTimeout(() => {
          retryDelay = Math.min(retryDelay * 2, 30000);
          connect();
        }, retryDelay);
      };
    };

    connect();

    return () => {
      stopped = true;
      cleanup();
    };
  }) as SubscriptionCallback<TOrderSchema>,
);

Percorso in questo repo

app/api/orders/[orderId]/subscribe/route.ts

Lato server (percorso API)

Utilizza intestazioni server basate su sessione tramitegenHeader.server(session), quindi chiama upstream${process.env.API_URL}/v5/orders/${params?.orderId}/subscribe. In caso di errore di connessione restituisce502.

Lato client (hook)

ApreEventSource a/api/orders/${referenceOrderId}/subscribe, convalida ogni payload conorderSchema.safeParse, gestiscestop eventi e si riconnette con backoff esponenziale.

9b

Traccia ordine (polling)

GET/v5/orders/{orderId}
Approccio di fallback: esegui il polling ogni 5-10 secondi fino a quando il pagamento non viene ricevuto. Il codice della carta regalo appare quando lo stato è 'Fatto'.
bash
curl -X GET 'https://api.cryptorefills.com/v5/orders/ord_abc123xyz' \
  -H 'Content-Type: application/json' \
  -H 'X-Cr-Application: YOUR_PARTNER_ID' \
  -H 'X-Cr-Version: YOUR_APP_VERSION'

Usa il polling quando

Non puoi mantenere aperta una connessione SSE, o il tuo ambiente client non supporta affidabilmente EventSource.

Stati tipici dell'ordine

WaitingForPayment -> WaitingForDelivery -> Done