Cost+Docs

PHP

SDK ufficiale PHP per il gateway di pagamento Cost+

SDK ufficiale PHP per il gateway di pagamento Cost+. Semplifica il flusso di reindirizzamento HPP (Pagina di Pagamento Ospitata), la firma dei payload HMAC e la verifica dei webhook.

Caratteristiche

  • Zero dipendenze esterne — utilizza solo estensioni PHP integrate (curl, json, hash)
  • PHP 8.1+ con proprietà readonly, argomenti nominati e tipi rigorosi
  • Generazione firma HMAC-SHA256 e verifica a tempo costante tramite hash_equals
  • Mappatura automatica snake_case/camelCase tra API e SDK
  • Analisi webhook + verifica dell'ordine basata su API
  • Testato su PHP 8.1, 8.2 e 8.3

Requisiti

  • PHP 8.1 o successivo
  • Estensioni: curl, json (entrambe incluse nel PHP standard)
  • Un account commerciante Cost+ — dashboard.costplus.io

Installazione

composer require nopayn/sdk

Guida Rapida

1. Inizializza il Client

use NoPayn\NoPaynClient;

$nopayn = new NoPaynClient([
    'apiKey'     => 'your-api-key',
    'merchantId' => 'your-project',
]);

2. Crea un Pagamento e Reindirizza all'HPP

$result = $nopayn->generatePaymentUrl([
    'amount'           => 1295,            // €12.95 in cents
    'currency'         => 'EUR',
    'merchantOrderId'  => 'ORDER-001',
    'description'      => 'Premium Widget',
    'returnUrl'        => 'https://shop.example.com/success',
    'failureUrl'       => 'https://shop.example.com/failure',
    'webhookUrl'       => 'https://shop.example.com/webhook',
    'locale'           => 'en-GB',
    'expirationPeriod' => 'PT30M',
]);

// Redirect the customer
// $result['orderUrl']   → HPP (customer picks payment method)
// $result['paymentUrl'] → direct link to the first transaction's payment method
// $result['signature']  → HMAC-SHA256 for verification
// $result['orderId']    → NoPayn order UUID
header('Location: ' . ($result['paymentUrl'] ?? $result['orderUrl']));

3. Gestisci il Webhook

$rawBody  = file_get_contents('php://input');
$verified = $nopayn->verifyWebhook($rawBody);

echo $verified['order']['status']; // 'completed', 'cancelled', etc.
echo $verified['isFinal'];        // true when the order won't change

if ($verified['order']['status'] === 'completed') {
    // Fulfil the order
}

http_response_code(200);

Riferimento API

new NoPaynClient(array $config)

ParametroTipoObbligatorioPredefinito
apiKeystring
merchantIdstring
baseUrlstringNohttps://api.nopayn.co.uk

$client->createOrder(array $params): array

Crea un ordine tramite POST /v1/orders/.

ParametroTipoObbligatorioDescrizione
amountintImporto nell'unità valutaria più piccola (centesimi)
currencystringCodice ISO 4217 (EUR, GBP, USD, NOK, SEK)
merchantOrderIdstringNoIl tuo riferimento interno dell'ordine
descriptionstringNoDescrizione dell'ordine
returnUrlstringNoReindirizzamento dopo pagamento riuscito
failureUrlstringNoReindirizzamento in caso di annullamento/scadenza/errore
webhookUrlstringNoNotifiche asincrone di cambio stato
localestringNoLingua HPP (en-GB, de-DE, nl-NL, ecc.)
paymentMethodsstring[]NoFiltra i metodi HPP
expirationPeriodstringNoDurata ISO 8601 (PT30M)

Metodi di pagamento disponibili: credit-card, apple-pay, google-pay, vipps-mobilepay

$client->getOrder(string $orderId): array

Recupera i dettagli dell'ordine tramite GET /v1/orders/{id}/.

$client->createRefund(string $orderId, int $amount, ?string $description = null): array

Emette un rimborso totale o parziale tramite POST /v1/orders/{id}/refunds/.

$client->generatePaymentUrl(array $params): array

Metodo di convenienza che crea un ordine e restituisce:

[
    'orderId'    => string,   // NoPayn order UUID
    'orderUrl'   => string,   // HPP URL
    'paymentUrl' => ?string,  // Direct payment URL (first transaction)
    'signature'  => string,   // HMAC-SHA256 of amount:currency:orderId
    'order'      => array,    // Full order object
]

$client->generateSignature(int $amount, string $currency, string $orderId): string

Genera una firma HMAC-SHA256 esadecimale.

$client->verifySignature(int $amount, string $currency, string $orderId, string $signature): bool

Verifica a tempo costante di una firma HMAC-SHA256.

$client->verifyWebhook(string $rawBody): array

Analizza il corpo del webhook, poi chiama GET /v1/orders/{id}/ per verificare lo stato effettivo.

Utility HMAC Standalone

use NoPayn\Signature;

$sig = Signature::generate('your-api-key', 1295, 'EUR', 'order-uuid');
$ok  = Signature::verify('your-api-key', 1295, 'EUR', 'order-uuid', $sig);

Gestione degli Errori

use NoPayn\Exceptions\ApiException;
use NoPayn\Exceptions\NoPaynException;
use NoPayn\Exceptions\WebhookException;

try {
    $nopayn->createOrder(['amount' => 100, 'currency' => 'EUR']);
} catch (ApiException $e) {
    echo $e->getStatusCode(); // 401, 400, etc.
    print_r($e->getErrorBody()); // Raw API error response
} catch (NoPaynException $e) {
    echo $e->getMessage(); // Network or parsing error
}

Stati dell'Ordine

StatoFinale?Descrizione
newNoOrdine creato
processingNoPagamento in corso
completedPagamento riuscito — consegna la merce
cancelledPagamento annullato dal cliente
expiredLink di pagamento scaduto
errorErrore tecnico

Best Practice per i Webhook

  1. Verifica sempre tramite API — il payload del webhook contiene solo l'ID dell'ordine, mai lo stato. Il metodo verifyWebhook() dell'SDK lo fa automaticamente.
  2. Restituisci HTTP 200 per confermare la ricezione. Qualsiasi altro codice attiva fino a 10 tentativi (ogni 2 minuti).
  3. Implementa un poller di backup — per gli ordini più vecchi di 10 minuti che non hanno raggiunto uno stato finale, interroga getOrder() come rete di sicurezza.
  4. Sii idempotente — potresti ricevere lo stesso webhook più volte.

Carte di Test

Usa queste carte in modalità test Cost+ (sito web sandbox):

CartaNumeroNote
Visa (successo)4111 1111 1111 1111Qualsiasi CVV
Mastercard (successo)5544 3300 0003 7Qualsiasi CVV
Visa (rifiutata)4111 1111 1111 1105Do Not Honor
Visa (fondi insufficienti)4111 1111 1111 1151Insufficient Funds

Usa qualsiasi data di scadenza futura e qualsiasi CVC a 3 cifre.

App Demo

Un'app demo basata su Docker è inclusa nel repository GitHub per testare il flusso di pagamento completo.

Supporto

Hai bisogno di aiuto? Contatta il nostro team di supporto a support@costplus.io.

On this page