Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

How to Accept Crypto Payments in PHP and Node.js Using Invoices and Webhooks

Accepting cryptocurrency payments in a web application becomes straightforward when you treat payments as an event-driven state machine rather than a single checkout redirect. Instead of relying on a user staying on a co

Accepting cryptocurrency payments in a web application becomes straightforward when you treat payments as an event-driven state machine rather than a single checkout redirect. Instead of relying on a user staying on a confirmation screen or polling your database repeatedly, you create an invoice on your backend, let the customer pay, and let webhooks drive order fulfillment and balance updates reliably.

In this guide, we walk through how to accept crypto payments and manage multi-asset balances with Vanryx (https://vanryx.com and https://app.vanryx.com), using the PHP SDK (vanryx/vanryx-php) and Node.js SDK (@vanryx/sdk).

1. How Invoices and Webhooks Fit Together

When integrating crypto checkout into an application, a clean workflow follows four steps:

  1. Create an invoice server-side: Your backend creates an invoice tied to your internal order ID, amount, currency, and asset, keeping your API key secret on the server.
  2. Present payment details to the customer: Your frontend displays the payment details or redirects the customer to complete the transfer.
  3. Receive webhook notifications: Vanryx sends webhook events when payment status changes (such as detected/pending, confirmed/completed, expired, or underpaid).
  4. Reconcile state and balances idempotently: Your webhook handler verifies authenticity, deduplicates events by ID, updates your order state, and reflects multi-asset balances in your system and in https://app.vanryx.com.

If a customer is paying for a specific order or cart, invoices are the cleanest fit. If you are building persistent user accounts where customers fund balances repeatedly over time, pair invoices for single orders with static deposit addresses for ongoing account top-ups.

2. Accepting Payments in PHP (vanryx/vanryx-php)

Install the PHP SDK with Composer:

composer require vanryx/vanryx-php

Create a server-side service that initializes VanryxClient using an environment variable and creates an invoice linked to your order reference:

<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Vanryx\VanryxClient;

final class VanryxInvoiceService
{
    private VanryxClient $client;

    public function __construct(string $apiKey)
    {
        if ($apiKey === '') {
            throw new InvalidArgumentException('VANRYX_API_KEY is required');
        }

        $this->client = new VanryxClient([
            'api_key' => $apiKey,
        ]);
    }

    public function createOrderInvoice(
        string $orderId,
        string $amount,
        string $currency = 'USD',
        string $asset = 'USDT'
    ): array {
        return $this->client->invoices->create([
            'order_id' => $orderId,
            'amount' => $amount,
            'currency' => $currency,
            'asset' => $asset,
        ]);
    }
}

$service = new VanryxInvoiceService((string) getenv('VANRYX_API_KEY'));
$invoice = $service->createOrderInvoice('ord_10042', '49.00', 'USD', 'USDT');

echo 'Created invoice ID: ' . ($invoice['id'] ?? 'n/a') . PHP_EOL;

Keep VANRYX_API_KEY exclusively on your backend server never in frontend JavaScript, Nuxt/Vue client bundles, or public environment variables.

3. Accepting Payments in Node.js (@vanryx/sdk)

Install the Node.js SDK:

npm install @vanryx/sdk

Create a backend helper module that instantiates VanryxClient and creates invoices for orders or services:

import { VanryxClient } from '@vanryx/sdk';

export function getVanryxClient(apiKey = process.env.VANRYX_API_KEY) {
  if (!apiKey) {
    throw new Error('Missing VANRYX_API_KEY');
  }

  return new VanryxClient({ apiKey });
}

export async function createCheckoutInvoice({
  orderId,
  amount,
  currency = 'USD',
  asset = 'USDT',
}) {
  const client = getVanryxClient();

  return client.invoices.create({
    order_id: orderId,
    amount,
    currency,
    asset,
  });
}

4. Handling Webhooks Safely in Production

Never treat a frontend redirect alone as proof of payment. Users can close their browser before or after a transaction is broadcast or confirmed, so your backend should rely on webhooks to advance order and balance states.

Follow these essential webhook practices:

  • Verify signatures first: Check incoming signature headers against your webhook secret before trusting payload fields or modifying database records.
  • Make event processing idempotent: Networks and webhook delivery pipelines can retry events. Store each processed event.id with a unique index in your database so a duplicate delivery never fulfills an order or credits a balance twice.
  • Guard state transitions: Keep intermediate states distinct from settled/confirmed states, and handle edge cases like expired or underpaid requests explicitly before unlocking goods or services.
  • Respond promptly with 2xx: Validate, persist/enqueue the event cleanly, and return a 2xx status code so delivery retries stay minimal.

Here is an Express webhook route example illustrating this structure:

import express from 'express';

const router = express.Router();

async function hasProcessedEvent(eventId) {
  // Query your database for an existing processed event ID
  return false;
}

async function markEventAsProcessed(eventId) {
  // Insert eventId into a unique-indexed processed_events table
}

router.post('/webhooks/vanryx', express.json(), async (req, res) => {
  try {
    const signature = req.header('x-vanryx-signature');
    if (!signature) {
      return res.status(401).json({ error: 'Missing webhook signature' });
    }

    // Verify signature using your webhook secret before processing payload
    const event = req.body;
    const eventId = event?.id;

    if (!eventId) {
      return res.status(400).json({ error: 'Missing event ID' });
    }

    if (await hasProcessedEvent(eventId)) {
      return res.status(200).json({ received: true, duplicate: true });
    }

    // Update order status or multi-asset balance records here
    await markEventAsProcessed(eventId);

    return res.status(200).json({ received: true });
  } catch (err) {
    console.error('Webhook handling failed:', err);
    return res.status(500).json({ error: 'Webhook processing error' });
  }
});

export default router;

5. Multi-Asset Balances and Operational Workflow

Once you accept multiple coins and tokens, keep your internal ledger and operational monitoring clear:

  • Track asset and network context: Separate balances and accounting records by asset ticker and network rather than blending raw figures.
  • Keep an audit trail: Store payment events, settlements, fees, and internal balance changes cleanly alongside current state.
  • Manage balances in the workspace: Teams can monitor multi-asset balances and payment activity in https://app.vanryx.com, with fees starting from 0.5% and 0% internal transfers.

Resources

How do you currently handle webhook retries or multi-asset accounting in your payment flows?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.