PHP code example of foisalislambd / nowpayments-php

1. Go to this page and download the library: Download foisalislambd/nowpayments-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

foisalislambd / nowpayments-php example snippets



NowPayments\NowPayments;

$np = new NowPayments([
    'apiKey' => getenv('NOWPAYMENTS_API_KEY'),
    'sandbox' => true,  // false for production
]);

// Create payment
$payment = $np->createPayment([
    'price_amount' => 29.99,
    'price_currency' => 'usd',
    'pay_currency' => 'btc',
    'order_id' => 'order-123',
]);

echo "Pay {$payment['pay_amount']} BTC → {$payment['pay_address']}\n";

$np = new NowPayments([
    'apiKey'    => 'your_api_key',
    'sandbox'   => true,
    'timeout'   => 30,
    'ipnSecret' => 'your_ipn_secret',  // for verifyIpn()
    'baseUrl'   => null,               // optional override
]);

$status = $np->getStatus();
// ['message' => 'OK', ...]

$auth = $np->getAuthToken('[email protected]', 'password');
$token = $auth['token'];
// Token expires in 5 min. Use for createPayout, verifyPayout, createSubPartner, etc.

$result = $np->getCurrencies();
// ['currencies' => ['btc', 'eth', 'usdt', 'trx', ...]]

// With fixed rate min/max:
$result = $np->getCurrencies(true);

$result = $np->getFullCurrencies();
// ['currencies' => [['id' => 1, 'code' => 'btc', 'name' => 'Bitcoin', 'wallet_regex' => '...', ...], ...]]

$result = $np->getMerchantCoins();
// ['currencies' => ['btc', 'eth', ...]]

$info = $np->getCurrency('btc');
// ['id' => 1, 'code' => 'btc', 'name' => 'Bitcoin', ...]

$payment = $np->createPayment([
    'price_amount'      => 29.99,
    'price_currency'    => 'usd',
    'pay_currency'      => 'btc',
    'order_id'          => 'order-12345',
    'order_description' => 'Monthly plan',
    'ipn_callback_url'  => 'https://yoursite.com/webhook',  // optional
    'is_fixed_rate'     => true,       // optional
    'is_fee_paid_by_user' => false,   // optional
]);

// Show to customer:
echo "Pay {$payment['pay_amount']} " . strtoupper($payment['pay_currency']) . "\n";
echo "To: {$payment['pay_address']}\n";

$payment = $np->getPaymentStatus(5524759814);
echo $payment['payment_status'];  // 'waiting' | 'finished' | 'expired' | ...

$list = $np->getPayments([
    'limit'   => 10,
    'page'    => 0,
    'sortBy'  => 'created_at',
    'orderBy' => 'desc',
    'dateFrom' => '2024-01-01',
    'dateTo'   => '2024-12-31',
]);
// $list['data'], $list['total'], $list['pagesCount']

$result = $np->updatePaymentEstimate($paymentId);
// $result['pay_amount'], $result['expiration_estimate_date']

$estimate = $np->getEstimatePrice([
    'amount'         => 100,
    'currency_from'  => 'usd',
    'currency_to'    => 'btc',
]);
echo "100 USD ≈ {$estimate['estimated_amount']} BTC\n";

$min = $np->getMinAmount([
    'currency_from'       => 'usd',
    'currency_to'         => 'btc',
    'fiat_equivalent'     => 'usd',   // optional
    'is_fixed_rate'       => false,   // optional
    'is_fee_paid_by_user' => false,  // optional
]);
echo $min['min_amount'] . ' ' . $min['fiat_equivalent'];

$invoice = $np->createInvoice([
    'price_amount'       => 49.99,
    'price_currency'     => 'usd',
    'pay_currency'       => 'btc',  // optional
    'order_id'           => 'inv-001',
    'order_description'  => 'Premium',
    'success_url'        => 'https://yoursite.com/success',
    'cancel_url'         => 'https://yoursite.com/cancel',
    'partially_paid_url' => 'https://yoursite.com/partial',  // optional
    'is_fixed_rate'      => true,
    'is_fee_paid_by_user' => false,
]);
// Redirect customer to: $invoice['invoice_url']

$payment = $np->createInvoicePayment([
    'iid'               => $invoiceId,
    'pay_currency'      => 'btc',
    'purchase_id'       => 'purchase-123',
    'order_description' => 'Item',
    'customer_email'    => '[email protected]',
]);

$auth = $np->getAuthToken($email, $password);
$token = $auth['token'];

try {
    $np->validatePayoutAddress(['address' => '0x...', 'currency' => 'eth']);
    echo "Valid\n";
} catch (NowPayments\NowPaymentsError $e) {
    echo "Invalid\n";
}

$batch = $np->createPayout([
    'ipn_callback_url' => 'https://yoursite.com/payout-webhook',
    'withdrawals' => [
        ['address' => 'TEmGw...', 'currency' => 'trx', 'amount' => 200],
        ['address' => '0x1EB...', 'currency' => 'eth', 'amount' => 0.1],
        // Scheduled: ['address' => '...', 'currency' => 'trx', 'amount' => 100, 'execute_at' => '2024-12-31T10:00:00Z']
    ],
], $token);
// $batch['id'], $batch['withdrawals']

$np->verifyPayout($batch['id'], '123456', $token);

// Use individual payout id, not batch id
$np->cancelPayout('5000000000', $token);

$status = $np->getPayoutStatus('5000000713', $token);

$payouts = $np->getPayouts([
    'batch_id'  => '5000000713',
    'status'    => 'finished',
    'limit'     => 10,
    'page'      => 0,
    'order_by'  => 'dateCreated',
    'order'     => 'desc',
]);

$result = $np->getFiatPayoutsCryptoCurrencies(['provider' => 'transfi'], $token);
// $result['result']

$result = $np->getFiatPayoutsPaymentMethods(
    ['provider' => 'transfi', 'currency' => 'usd'],
    $token
);

$result = $np->getFiatPayouts([
    'status'   => 'FINISHED',
    'limit'    => 10,
    'dateFrom' => '2024-01-01',
], $token);
// $result['result']['rows']

$balance = $np->getBalance($token);
// ['eth' => ['amount' => 0.5, 'pendingAmount' => 0], 'trx' => [...], ...]

$plans = $np->getSubscriptionPlans(['limit' => 10, 'offset' => 0]);
// $plans['result'], $plans['count']

$plan = $np->getSubscriptionPlan('76215585');
// $plan['result']

$np->updateSubscriptionPlan('76215585', [
    'amount'       => 9.99,
    'interval_day' => '30',
]);

// Email subscription:
$result = $np->createSubscription([
    'subscription_plan_id' => 76215585,
    'email' => '[email protected]',
], $token);

// Custody (sub-partner):
$result = $np->createSubscription([
    'subscription_plan_id' => 76215585,
    'sub_partner_id'      => '111394288',
], $token);
// $result['result']

$list = $np->getSubscriptions([
    'status'               => 'PAID',
    'subscription_plan_id' => '111394288',
    'is_active'            => true,
    'limit'                => 10,
    'offset'               => 0,
]);

$sub = $np->getSubscription('1515573197');
$np->deleteSubscription('1515573197', $token);

$result = $np->createSubPartner('user-123', $token);
// $result['result']['id'], $result['result']['name']

$result = $np->createSubPartnerPayment([
    'currency'       => 'trx',
    'amount'         => 50,
    'sub_partner_id' => '1631380403',
    'fixed_rate'     => false,
], $token);
// Show customer: Pay $result['result']['pay_amount'] TRX to $result['result']['pay_address']

$users = $np->getSubPartners(['offset' => 0, 'limit' => 10, 'order' => 'DESC'], $token);

$balance = $np->getSubPartnerBalance('111394288');
// $balance['result']['balances']['usdtbsc']['amount']

$np->createTransfer([
    'currency' => 'trx',
    'amount'  => 0.3,
    'from_id' => 111394288,
    'to_id'   => 5209391548,
], $token);

$np->deposit([
    'currency'       => 'trx',
    'amount'         => 0.5,
    'sub_partner_id' => '111394288',
], $token);

$np->writeOff([
    'currency'       => 'trx',
    'amount'         => 0.3,
    'sub_partner_id' => '111394288',
], $token);

$transfers = $np->getTransfers(['status' => 'FINISHED', 'limit' => 10], $token);
$transfer = $np->getTransfer('327209161', $token);

$np->createConversion([
    'amount'        => 50,
    'from_currency' => 'usdttrc20',
    'to_currency'   => 'usdterc20',
], $token);

$status = $np->getConversionStatus('1327866232', $token);
$list = $np->getConversions(['status' => 'FINISHED', 'limit' => 10], $token);

$np = new NowPayments([
    'apiKey'    => '...',
    'ipnSecret' => 'SECRET',
]);

// In your webhook handler (Laravel, Slim, plain PHP):
$payload   = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_NOWPAYMENTS_SIG'] ?? '';

if ($np->verifyIpn($payload, $signature)) {
    $data = json_decode($payload, true);
    // Process: $data['payment_id'], $data['payment_status'], etc.
}

use NowPayments\Ipn;

$valid = Ipn::verifySignature($payload, $signature, 'SECRET');

// Create signature for testing:
$sig = Ipn::createSignature($payloadArray, 'SECRET');

use NowPayments\Helpers;
use NowPayments\Constants;

$payment = $np->getPaymentStatus($id);

// Human-readable status
Helpers::getStatusLabel($payment['payment_status']);
// "Awaiting payment" | "Completed" | "Failed" | ...

// Status checks
Helpers::isPaymentComplete($payment['payment_status']);  // finished, failed, refunded, expired
Helpers::isPaymentPending($payment['payment_status']);   // waiting, confirming, ...

// Summary string
Helpers::getPaymentSummary($payment);
// "Awaiting payment: 0.001234 BTC → bc1q..."

// Constants
Constants::PAYMENT_STATUS_LABELS;
Constants::PAYMENT_STATUSES;
Constants::PAYMENT_DONE_STATUSES;
Constants::PAYMENT_PENDING_STATUSES;

use NowPayments\NowPaymentsError;

try {
    $np->createPayment([...]);
} catch (NowPaymentsError $e) {
    echo $e->getMessage();      // "Invalid api key"
    echo $e->getStatusCode();   // 401
    echo $e->getErrorCode();    // API error code if any
    echo $e->getResponse();     // Raw response data
    echo (string) $e;          // "Invalid api key (status: 401)"
}
bash
composer 
bash
composer 
bash
# Set your API key
export NOWPAYMENTS_API_KEY=your_key

# Run examples
php examples/01-create-payment.php
php examples/02-check-status.php 12345678