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/sdkGuida 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)
| Parametro | Tipo | Obbligatorio | Predefinito |
|---|---|---|---|
apiKey | string | Sì | — |
merchantId | string | Sì | — |
baseUrl | string | No | https://api.nopayn.co.uk |
$client->createOrder(array $params): array
Crea un ordine tramite POST /v1/orders/.
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
amount | int | Sì | Importo nell'unità valutaria più piccola (centesimi) |
currency | string | Sì | Codice ISO 4217 (EUR, GBP, USD, NOK, SEK) |
merchantOrderId | string | No | Il tuo riferimento interno dell'ordine |
description | string | No | Descrizione dell'ordine |
returnUrl | string | No | Reindirizzamento dopo pagamento riuscito |
failureUrl | string | No | Reindirizzamento in caso di annullamento/scadenza/errore |
webhookUrl | string | No | Notifiche asincrone di cambio stato |
locale | string | No | Lingua HPP (en-GB, de-DE, nl-NL, ecc.) |
paymentMethods | string[] | No | Filtra i metodi HPP |
expirationPeriod | string | No | Durata 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
| Stato | Finale? | Descrizione |
|---|---|---|
new | No | Ordine creato |
processing | No | Pagamento in corso |
completed | Sì | Pagamento riuscito — consegna la merce |
cancelled | Sì | Pagamento annullato dal cliente |
expired | Sì | Link di pagamento scaduto |
error | Sì | Errore tecnico |
Best Practice per i Webhook
- 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. - Restituisci HTTP 200 per confermare la ricezione. Qualsiasi altro codice attiva fino a 10 tentativi (ogni 2 minuti).
- 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. - Sii idempotente — potresti ricevere lo stesso webhook più volte.
Carte di Test
Usa queste carte in modalità test Cost+ (sito web sandbox):
| Carta | Numero | Note |
|---|---|---|
| Visa (successo) | 4111 1111 1111 1111 | Qualsiasi CVV |
| Mastercard (successo) | 5544 3300 0003 7 | Qualsiasi CVV |
| Visa (rifiutata) | 4111 1111 1111 1105 | Do Not Honor |
| Visa (fondi insufficienti) | 4111 1111 1111 1151 | Insufficient 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.