Скопіюйте, вставте — і приймайте платіж.
Один рядок для встановлення, кілька — щоб прийняти платіж. Офіційні SDK для Node.js, Python, PHP, Go, C#, Ruby, Java, Rust і C++, рецепти для Express і Next.js, а також «сирі» HTTP-виклики, які вони всі обгортають. Кожен фрагмент написано на основі реального коду бібліотеки.
const invoice = await receivify.createInvoice(
{
amount_fiat: '25.00',
currency: 'USD',
asset: 'btc',
reference: `order-${order.id}`,
},
{ idempotencyKey: `order-${order.id}` },
)Дев’ять офіційних SDK, один API
Кожен обгортає ті самі REST-виклики й бере на себе складні частини: підписи, ідемпотентність, точні суми.
Читати документаціюESM, нуль залежностей під час виконання, рукописні декларації TypeScript. Node 18+.
Код на GitHubЗавантажити (.zip)Приклад: ExpressПриклад: Next.js (App Router)
npm install receivifyimport { Receivify } from 'receivify'
export const receivify = new Receivify(
process.env.RECEIVIFY_URL,
process.env.RECEIVIFY_API_KEY,
{ webhookSecrets: [process.env.RECEIVIFY_WEBHOOK_SECRET] },
)const invoice = await receivify.createInvoice(
{
amount_fiat: '25.00',
currency: 'USD',
asset: 'btc',
reference: `order-${order.id}`,
},
{ idempotencyKey: `order-${order.id}` },
)
// Simplest path: send them to the hosted page.
redirect(invoice.checkout_url)import { formatUnits, compareAmounts } from 'receivify'
// invoice.address — where the customer sends funds
// invoice.amount_expected — base units, as a STRING
// invoice.payment_uri — BIP-21 URI for the QR code (null on EVM/SOL/TRON)
// invoice.expires_at — ISO timestamp for your countdown
const display = formatUnits(invoice.amount_expected, 8) // '0.00123456'
const paid = compareAmounts(invoice.amount_received, invoice.amount_expected) >= 0import { SIGNATURE_HEADER } from 'receivify'
app.post('/webhooks/receivify',
express.raw({ type: 'application/json' }), // a Buffer: the exact bytes we signed
(req, res) => {
let event
try {
// parseWebhook verifies AND decodes. verifyWebhook returns a boolean.
event = receivify.parseWebhook(req.body, req.get(SIGNATURE_HEADER))
} catch {
return res.sendStatus(400) // bad signature, stale timestamp, or bad JSON
}
if (event.event === 'invoice.paid') fulfil(event.data.reference)
res.sendStatus(200) // 2xx quickly, then do the work
})SDK Node у застосунку Express: маршрут оплати, маршрут webhook, сторінка замовлення.
npm install receivify express// receivify.js
import { Receivify } from 'receivify'
export const receivify = new Receivify(
process.env.RECEIVIFY_URL,
process.env.RECEIVIFY_API_KEY,
{ webhookSecrets: [process.env.RECEIVIFY_WEBHOOK_SECRET] },
)import express from 'express'
const app = express()
// The webhook route gets the RAW bytes...
app.use('/webhooks/receivify', express.raw({ type: 'application/json' }))
// ...everything else can have parsed JSON. Order matters: a global
// express.json() mounted above this line would win and the signature
// would never verify.
app.use(express.json())app.post('/checkout/:orderId', async (req, res, next) => {
try {
const invoice = await receivify.createInvoice(
{
amount_fiat: req.body.total, // '25.00'
currency: 'USD',
asset: 'btc',
reference: `order-${req.params.orderId}`,
},
{ idempotencyKey: `order-${req.params.orderId}` },
)
res.redirect(303, invoice.checkout_url)
} catch (err) { next(err) }
})import { SIGNATURE_HEADER } from 'receivify'
app.post('/webhooks/receivify', (req, res) => {
let event
try {
event = receivify.parseWebhook(req.body, req.get(SIGNATURE_HEADER))
} catch {
return res.sendStatus(400)
}
res.sendStatus(200) // acknowledge first
// (event, sequence) is the de-duplication key — there is no separate id.
if (alreadyHandled(event.event, event.sequence)) return
if (event.event === 'invoice.paid') fulfil(event.data.reference)
})Server Action відповідає за оплату, Route Handler за webhook. Секрети в браузер не потрапляють.
npm install receivify// lib/receivify.js
import 'server-only'
import { Receivify } from 'receivify'
export const receivify = new Receivify(
process.env.RECEIVIFY_URL,
process.env.RECEIVIFY_API_KEY, // never NEXT_PUBLIC_
{ webhookSecrets: [process.env.RECEIVIFY_WEBHOOK_SECRET] },
)'use server'
import { redirect } from 'next/navigation'
import { receivify } from '@/lib/receivify'
export async function startCheckout(orderId, total) {
let invoice
try {
invoice = await receivify.createInvoice(
{ amount_fiat: total, currency: 'GBP', asset: 'btc', reference: `order-${orderId}` },
{ idempotencyKey: `order-${orderId}` },
)
} catch (err) {
return { error: 'Could not start checkout.' }
}
redirect(invoice.checkout_url) // outside the try — see above
}// app/api/webhooks/receivify/route.js
import { SIGNATURE_HEADER } from 'receivify'
import { receivify } from '@/lib/receivify'
export const runtime = 'nodejs' // node:crypto — not the edge runtime
export const dynamic = 'force-dynamic' // never cache a webhook
export async function POST(request) {
const raw = await request.text() // RAW bytes, not request.json()
let event
try {
event = receivify.parseWebhook(raw, request.headers.get(SIGNATURE_HEADER))
} catch {
return new Response('bad signature', { status: 400 })
}
if (event.event === 'invoice.paid') {
await fulfil(event.data.reference)
}
return new Response('ok')
}import { revalidatePath } from 'next/cache'
// inside the webhook handler, after fulfilling:
revalidatePath(`/orders/${event.data.reference}`)Лише стандартна бібліотека. Python 3.9+, повна типізація.
Код на GitHubЗавантажити (.zip)Приклад: FlaskПриклад: FastAPI
pip install receivifyimport os
from receivify import Receivify
rcv = Receivify(
"https://receivify.io",
os.environ["RECEIVIFY_API_KEY"],
webhook_secrets=[os.environ["RECEIVIFY_WEBHOOK_SECRET"]],
)invoice = rcv.create_invoice(
amount_fiat="25.00",
currency="USD",
asset="btc",
reference=f"order-{order.id}",
idempotency_key=f"order-{order.id}",
)
return redirect(invoice.checkout_url) # Invoice is a dataclass — attribute accessfrom receivify import money
address = invoice.address
amount = money.format_amount(invoice.amount_expected, 8) # '0.00123456'
uri = invoice.payment_uri # BIP-21, for the QR code
expires = invoice.expires_at
# Python ints are arbitrary-precision, so int() on a base-unit string is exact.
paid = int(invoice.amount_received) >= int(invoice.amount_expected)from receivify import SIGNATURE_HEADER, SignatureVerificationError, WebhookPayloadError
@app.post("/webhooks/receivify")
def webhook():
try:
# parse_webhook verifies AND decodes; verify_webhook returns a bool.
event = rcv.parse_webhook(
request.get_data(), # RAW bytes, not request.json
request.headers.get(SIGNATURE_HEADER),
)
except (SignatureVerificationError, WebhookPayloadError):
return "", 400 # bad signature, stale timestamp, or bad JSON
if event.event == "invoice.paid": # WebhookEvent is a dataclass
fulfil(event.invoice.reference)
return "", 200Один файл, без залежностей. Встановіть через Composer або просто додайте Receivify.php у будь-який проєкт. PHP 7.4+.
Код на GitHubЗавантажити (.zip)Приклад: LaravelПриклад: Plain PHP
composer config repositories.receivify vcs https://github.com/receivify/receivify-php
composer require receivify/receivifyrequire __DIR__ . '/vendor/autoload.php';
$rcv = new Receivify('https://receivify.io', getenv('RECEIVIFY_API_KEY'), [
'webhook_secrets' => array_filter([
getenv('RECEIVIFY_WEBHOOK_SECRET'),
getenv('RECEIVIFY_WEBHOOK_SECRET_PREVIOUS'),
]),
'timeout' => 30,
]);$invoice = $rcv->createInvoice([
'amount_fiat' => '25.00',
'currency' => 'USD',
'asset' => 'btc',
'reference' => 'order-' . $order->id,
], ['idempotency_key' => 'order-' . $order->id]);
header('Location: ' . $invoice['checkout_url']);$address = $invoice['address'];
$amount = Receivify::fromBaseUnits($invoice['amount_expected'], 8); // '0.00123456'
$uri = $invoice['payment_uri']; // BIP-21, for the QR code
$expires = $invoice['expires_at'];
// bcmath: exact comparison of two integer strings, no float anywhere.
$paid = bccomp($invoice['amount_received'], $invoice['amount_expected']) >= 0;$raw = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_RECEIVIFY_SIGNATURE'] ?? '';
try {
// parseWebhook verifies AND decodes; verifyWebhook returns a bool.
$event = $rcv->parseWebhook($raw, $sig);
} catch (ReceivifyException $e) { // bad signature, stale timestamp, or bad JSON
http_response_code(400);
exit;
}
if ($event['event'] === 'invoice.paid') {
fulfil($event['data']['reference']);
}
http_response_code(200);.NET 8, з урахуванням nullable, один спільний HttpClient. Потокобезпечний.
Код на GitHubЗавантажити (.zip)Приклад: ASP.NET Core minimal API
# From the download or a clone of the SDK repository:
dotnet add reference receivify-csharp/src/Receivify/Receivify.csprojusing Receivify;
var client = new ReceivifyClient(
apiUrl: "https://receivify.io",
apiKey: Environment.GetEnvironmentVariable("RECEIVIFY_API_KEY"),
options: new ReceivifyClientOptions
{
WebhookSecrets = new[] { Environment.GetEnvironmentVariable("RECEIVIFY_WEBHOOK_SECRET") },
});var invoice = await client.CreateInvoiceAsync(
new InvoiceCreateRequest
{
AmountFiat = "25.00",
Currency = "USD",
Asset = "btc",
Reference = $"order-{order.Id}",
},
new RequestOptions { IdempotencyKey = $"order-{order.Id}" });
return Redirect(invoice.CheckoutUrl);var address = invoice.Address;
var amount = Money.Format(invoice.AmountExpected, 8); // "0.00123456"
var uri = invoice.PaymentUri; // BIP-21, for the QR code
var expires = invoice.ExpiresAt;
bool paid = Money.Compare(invoice.AmountReceived, invoice.AmountExpected) >= 0;[HttpPost("/webhooks/receivify")]
public async Task<IActionResult> Webhook()
{
using var reader = new StreamReader(Request.Body);
var raw = await reader.ReadToEndAsync();
WebhookEvent evt;
try
{
// ParseWebhook verifies AND deserialises; VerifyWebhook returns a bool.
evt = client.ParseWebhook(raw, Request.Headers["X-Receivify-Signature"]);
}
catch (ReceivifyWebhookException)
{
return BadRequest();
}
// Data is raw JSON; AsInvoiceData() types it for invoice.*, sweep.sent and test.
if (evt.Event == "invoice.paid") Fulfil(evt.AsInvoiceData()?.Reference);
return Ok();
}Лише стандартна бібліотека, підтримка context, типізовані помилки для errors.Is. Go 1.21+.
go get github.com/receivify/receivify-sdks/[email protected]import receivify "github.com/receivify/receivify-sdks/go"
client, err := receivify.NewClient(
os.Getenv("RECEIVIFY_URL"),
os.Getenv("RECEIVIFY_API_KEY"),
receivify.WithWebhookSecrets(os.Getenv("RECEIVIFY_WEBHOOK_SECRET")),
)
if err != nil {
log.Fatal(err)
}inv, err := client.CreateInvoice(r.Context(), &receivify.CreateInvoiceParams{
AmountFiat: "25.00",
Currency: "USD",
Asset: "btc", // or Asset: "usdc", Chain: "base"
Reference: "order-" + orderID,
}, receivify.RequestOptions{IdempotencyKey: "order-" + orderID})
if err != nil {
http.Error(w, "could not create invoice", http.StatusBadGateway)
return
}
http.Redirect(w, r, inv.CheckoutURL, http.StatusSeeOther)http.HandleFunc("/webhooks/receivify", func(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
event, err := client.ParseWebhook(raw, r.Header.Get(receivify.SignatureHeader))
if err != nil {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
if event.Event == receivify.EventInvoicePaid {
data, _ := event.InvoiceData()
fulfil(data.Reference)
}
w.WriteHeader(http.StatusOK)
})Без залежностей під час виконання. Rails, Sinatra або чистий Ruby. Ruby 2.7+.
# Build and install it from the SDK repository:
git clone https://github.com/receivify/receivify-sdks.git
cd receivify-sdks/ruby && gem build receivify.gemspec && gem install ./receivify-1.1.0.gemrequire "receivify"
RECEIVIFY = Receivify::Client.new(
api_url: ENV.fetch("RECEIVIFY_URL", "https://receivify.io"),
api_key: ENV.fetch("RECEIVIFY_API_KEY"),
webhook_secrets: [ENV.fetch("RECEIVIFY_WEBHOOK_SECRET")]
)invoice = RECEIVIFY.create_invoice(
amount_fiat: "25.00",
currency: "USD",
asset: "btc", # or asset: "usdc", chain: "base"
reference: "order-#{order.id}",
idempotency_key: "order-#{order.id}"
)
redirect_to invoice.checkout_url, allow_other_host: trueclass ReceivifyWebhooksController < ActionController::Base
skip_forgery_protection
def create
event = RECEIVIFY.parse_webhook(request.raw_post, request.headers["X-Receivify-Signature"])
fulfil(event.data["reference"]) if event.event == "invoice.paid"
head :ok
rescue Receivify::SignatureVerificationError
head :bad_request
end
endJava 11+, нуль залежностей, білдери всюди. Працює з Kotlin без змін.
# Build it once into ~/.m2 from the SDK repository:
git clone https://github.com/receivify/receivify-sdks.git
cd receivify-sdks/java && mvn -q install
# then depend on io.receivify:receivify-java:1.1.0import io.receivify.*;
import java.util.List;
ReceivifyClient client = ReceivifyClient.builder()
.apiUrl(System.getenv("RECEIVIFY_URL"))
.apiKey(System.getenv("RECEIVIFY_API_KEY"))
.webhookSecrets(List.of(System.getenv("RECEIVIFY_WEBHOOK_SECRET")))
.build();Invoice invoice = client.createInvoice(
CreateInvoiceParams.builder()
.amountFiat("25.00").currency("USD")
.asset("btc") // or .asset("usdc").chain("base")
.reference("order-" + orderId)
.build(),
RequestOptions.idempotencyKey("order-" + orderId));
response.sendRedirect(invoice.getCheckoutUrl());@PostMapping(value = "/webhooks/receivify", consumes = "application/json")
public ResponseEntity<String> handle(
@RequestBody byte[] rawBody,
@RequestHeader(value = "X-Receivify-Signature", required = false) String signature) {
WebhookEvent event;
try {
event = Webhooks.parse(rawBody, signature, secrets);
} catch (SignatureVerificationException e) {
return ResponseEntity.status(400).body("bad signature");
}
if (EventNames.INVOICE_PAID.equals(event.getEvent())) {
fulfil(event.getInvoiceData().getReference());
}
return ResponseEntity.ok("ok");
}Блокувальний клієнт зі змінним транспортом; підключайте в axum, actix чи CLI. Rust 1.70+.
cargo add receivify --git https://github.com/receivify/receivify-sdksuse receivify::{Client, CreateInvoice, RequestOptions};
let client = Client::builder(std::env::var("RECEIVIFY_URL")?)
.api_key(std::env::var("RECEIVIFY_API_KEY")?)
.webhook_secrets(vec![std::env::var("RECEIVIFY_WEBHOOK_SECRET")?])
.build()?;let invoice = client.create_invoice(
&CreateInvoice {
amount_fiat: Some("25.00".into()),
currency: Some("USD".into()),
asset: Some("btc".into()), // or "usdc" with chain: Some("base".into())
reference: Some(format!("order-{order_id}")),
..Default::default()
},
Some(&RequestOptions::idempotency_key(format!("order-{order_id}"))),
)?;
// send the customer to invoice.checkout_urlasync fn receivify_webhook(State(client): State<Client>, headers: HeaderMap, body: Bytes) -> StatusCode {
let signature = headers.get("x-receivify-signature").and_then(|v| v.to_str().ok()).unwrap_or("");
let Ok(event) = client.parse_webhook(&body, signature) else {
return StatusCode::BAD_REQUEST;
};
if event.event == "invoice.paid" {
if let Ok(data) = event.invoice_data() {
fulfil(data.reference);
}
}
StatusCode::OK
}C++17, header-first, CMake. Єдині зовнішні залежності — libcurl і OpenSSL.
add_subdirectory(receivify-cpp)
target_link_libraries(app PRIVATE receivify)#include <receivify/receivify.hpp>
#include <cstdlib>
receivify::ClientOptions options;
options.webhook_secrets = { std::getenv("RECEIVIFY_WEBHOOK_SECRET") };
auto client = receivify::make_client(
"https://receivify.io",
std::getenv("RECEIVIFY_API_KEY"),
options);receivify::RequestOptions opts;
opts.idempotency_key = "order-" + std::to_string(order.id);
auto invoice = client.create_invoice(receivify::Json::object({
{"amount_fiat", receivify::Json("25.00")},
{"currency", receivify::Json("USD")},
{"asset", receivify::Json("btc")},
{"reference", receivify::Json("order-" + std::to_string(order.id))},
}), opts);
redirect(invoice.checkout_url);const auto& address = invoice.address;
const auto amount = receivify::units::format_units(invoice.amount_expected, 8);
const auto& uri = invoice.payment_uri; // std::optional — BIP-21, for the QR code
const auto& expires = invoice.expires_at;
bool paid = receivify::units::compare_amounts(
invoice.amount_received, invoice.amount_expected) >= 0;// verify_webhook returns a bool; parse_webhook returns the envelope.
if (!client.verify_webhook(raw_body, signature_header)) {
respond(400);
return;
}
const auto event = client.parse_webhook(raw_body, signature_header);
if (event.event == "invoice.paid") {
// event.data is raw Json; type it before reading fields.
const auto data = receivify::InvoiceEventData::from_json(event.data);
fulfil(data.reference.value_or(data.id));
}
respond(200);Чистий HTTP. Кожен SDK вище — тонка обгортка саме над цими викликами.
curl https://receivify.io/llms-full.txtcurl -X POST https://receivify.io/api/v1/invoices \
-H "Authorization: Bearer $RECEIVIFY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1234" \
-d '{
"amount_fiat": "25.00",
"currency": "USD",
"asset": "btc",
"reference": "order-1234"
}'{
"id": "b1f2…",
"status": "pending",
"address": "bc1q…",
"asset": "btc",
"amount_expected": "123456",
"amount_received": "0",
"amount_fiat": "25.00",
"fiat_currency": "USD",
"payment_uri": "bitcoin:bc1q…?amount=0.00123456",
"checkout_url": "https://receivify.io/pay/b1f2…",
"expires_at": "2026-01-01T12:00:00.000Z"
}curl https://receivify.io/api/v1/invoices/b1f2… \
-H "Authorization: Bearer $RECEIVIFY_API_KEY"# x-receivify-signature: t=1735689600,v1=9f86d0…
# signed payload is exactly: <t> + "." + <raw request body>
printf '%s' "$T.$RAW_BODY" \
| openssl dgst -sha256 -hmac "$RECEIVIFY_WEBHOOK_SECRET"Невелика бібліотека між вашим кодом і API.
Ваш код викликає SDK, SDK викликає API Receivify, а коли рахунок оплачено, повертається підписаний вебхук, який той самий SDK перевіряє одним викликом.
Маєте магазин? Встановіть плагін.
Кожен плагін — повноцінна реалізація з перевіркою HMAC-вебхуків: той самий контракт, що й у SDK вище, але вам нічого не треба писати.
WooCommerce
WordPress · завантажте ZIP у розділі «Плагіни → Додати новий»
OpenCart
OpenCart 3.0.x · скопіюйте upload/ поверх кореня магазину
Magento 2
Magento Open Source 2.4 · app/code/Receivify
PrestaShop
PrestaShop 8 · «Модулі → Завантажити модуль»
Почніть із магазину, який уже працює.
Кожен SDK має невеликий приклад магазину в репозиторії receivify-sdks.
node-express
- .env.exampleВаш API-ключ і секрет webhook
- orders.jsОновлення замовлення: позначає оплаченим лише webhook
- package.jsonSDK receivify
- server.jsМаршрути купівлі, перенаправлення на оплату та webhook
- // Receivify + Express: a complete, tiny shop.
- //
- // GET / product page with a "Pay with crypto" form
- // POST /checkout creates the order + a Receivify invoice, redirects to
- // checkout
- // GET /orders/:id order status page (where the customer comes back to)
- // POST /webhooks/receivify Receivify tells us what happened; the ONLY place an order is
- // marked paid
- //
- // Run: cp .env.example .env (fill it in) -> npm install -> npm start
- import express from 'express'
- import { Receivify, ReceivifyApiError, ReceivifyWebhookError, SIGNATURE_HEADER } from 'receivify'
- import { createOrder, getOrder, updateOrder } from './orders.js'
Питання про SDK
Для яких мов є офіційний SDK?
Node.js, Python, PHP, Go, C#, Ruby, Java (і Kotlin), Rust та C++. Є також готові приклади для Express і Next.js, а будь-яка інша мова може напряму звертатися до REST API.
SDK безкоштовні та з відкритим кодом?
Так. Кожен SDK безкоштовний, поширюється за ліцензією MIT і опублікований на GitHub, тож ви можете читати, форкати й перевіряти код, який встановлюєте.
Чи потрібен SDK, щоб приймати криптоплатежі?
Ні. SDK звільняє вас від написання складних частин самостійно, наприклад перевірки підпису webhook і ключів ідемпотентності. Будь-яка мова з HTTP-клієнтом може напряму використовувати API.
Де опубліковані SDK?
Пакети npm, PyPI та модулі Go для Node.js, Python і Go. Решта SDK встановлюються безпосередньо з їхнього репозиторію на GitHub: кожна картка і кожен посібник показують точну команду.
Як перевіряти webhook за допомогою SDK?
Передайте сире тіло запиту й заголовок підпису допоміжній функції webhook у SDK. Вона перевіряє HMAC-підпис і повертає декодовану подію або завершується помилкою, щоб ви могли відповісти 400.
Чи може ШІ-агент для програмування зібрати інтеграцію за мене?
Так. Вкажіть йому /llms-full.txt: весь API в одному документі Markdown, створеному з того самого контракту OpenAPI, якого дотримуються SDK.
Залишилися запитання? Запитати в чаті · Усі запитання
Почніть приймати крипту вже сьогодні.
Створіть безкоштовний акаунт, додайте адресу гаманця й прийміть перший платіж за лічені хвилини.