PHP
SDK officiel PHP pour la passerelle de paiement Cost+
SDK officiel PHP pour la passerelle de paiement Cost+. Simplifie le flux de redirection HPP (page de paiement hébergée), la signature de payload HMAC et la vérification des webhooks.
Fonctionnalités
- Zéro dépendance externe — utilise uniquement les extensions PHP intégrées (
curl,json,hash) - PHP 8.1+ avec propriétés readonly, arguments nommés et typage strict
- Génération de signature HMAC-SHA256 et vérification en temps constant via
hash_equals - Mappage automatique snake_case/camelCase entre l'API et le SDK
- Analyse des webhooks + vérification des commandes via l'API
- Testé sur PHP 8.1, 8.2 et 8.3
Prérequis
- PHP 8.1 ou ultérieur
- Extensions :
curl,json(toutes deux incluses dans PHP standard) - Un compte marchand Cost+ — dashboard.costplus.io
Installation
composer require nopayn/sdkDémarrage rapide
1. Initialiser le client
use NoPayn\NoPaynClient;
$nopayn = new NoPaynClient([
'apiKey' => 'your-api-key',
'merchantId' => 'your-project',
]);2. Créer un paiement et rediriger vers la 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. Gérer le 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);Référence API
new NoPaynClient(array $config)
| Paramètre | Type | Obligatoire | Par défaut |
|---|---|---|---|
apiKey | string | Oui | — |
merchantId | string | Oui | — |
baseUrl | string | Non | https://api.nopayn.co.uk |
$client->createOrder(array $params): array
Crée une commande via POST /v1/orders/.
| Paramètre | Type | Obligatoire | Description |
|---|---|---|---|
amount | int | Oui | Montant dans la plus petite unité monétaire (centimes) |
currency | string | Oui | Code ISO 4217 (EUR, GBP, USD, NOK, SEK) |
merchantOrderId | string | Non | Votre référence interne de commande |
description | string | Non | Description de la commande |
returnUrl | string | Non | Redirection après paiement réussi |
failureUrl | string | Non | Redirection en cas d'annulation/expiration/erreur |
webhookUrl | string | Non | Notifications asynchrones de changement de statut |
locale | string | Non | Langue de la HPP (en-GB, de-DE, nl-NL, etc.) |
paymentMethods | string[] | Non | Filtrer les méthodes HPP |
expirationPeriod | string | Non | Durée ISO 8601 (PT30M) |
Méthodes de paiement disponibles : credit-card, apple-pay, google-pay, vipps-mobilepay
$client->getOrder(string $orderId): array
Récupère les détails de la commande via GET /v1/orders/{id}/.
$client->createRefund(string $orderId, int $amount, ?string $description = null): array
Effectue un remboursement total ou partiel via POST /v1/orders/{id}/refunds/.
$client->generatePaymentUrl(array $params): array
Méthode utilitaire qui crée une commande et renvoie :
[
'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
Génère une signature HMAC-SHA256 hexadécimale.
$client->verifySignature(int $amount, string $currency, string $orderId, string $signature): bool
Vérification en temps constant d'une signature HMAC-SHA256.
$client->verifyWebhook(string $rawBody): array
Analyse le corps du webhook, puis appelle GET /v1/orders/{id}/ pour vérifier le statut réel.
Utilitaires HMAC autonomes
use NoPayn\Signature;
$sig = Signature::generate('your-api-key', 1295, 'EUR', 'order-uuid');
$ok = Signature::verify('your-api-key', 1295, 'EUR', 'order-uuid', $sig);Gestion des erreurs
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
}Statuts des commandes
| Statut | Final ? | Description |
|---|---|---|
new | Non | Commande créée |
processing | Non | Paiement en cours |
completed | Oui | Paiement réussi — livrez les marchandises |
cancelled | Oui | Paiement annulé par le client |
expired | Oui | Le lien de paiement a expiré |
error | Oui | Erreur technique |
Bonnes pratiques pour les webhooks
- Vérifiez toujours via l'API — le payload du webhook contient uniquement l'identifiant de la commande, jamais le statut. Le
verifyWebhook()du SDK le fait automatiquement. - Renvoyez HTTP 200 pour accuser réception. Tout autre code déclenche jusqu'à 10 tentatives (espacées de 2 minutes).
- Implémentez un polling de secours — pour les commandes de plus de 10 minutes qui n'ont pas atteint un statut final, interrogez
getOrder()comme filet de sécurité. - Soyez idempotent — vous pouvez recevoir le même webhook plusieurs fois.
Cartes de test
Utilisez ces cartes en mode test Cost+ (site web sandbox) :
| Carte | Numéro | Notes |
|---|---|---|
| Visa (succès) | 4111 1111 1111 1111 | N'importe quel CVV |
| Mastercard (succès) | 5544 3300 0003 7 | N'importe quel CVV |
| Visa (refusée) | 4111 1111 1111 1105 | Do Not Honor |
| Visa (fonds insuffisants) | 4111 1111 1111 1151 | Insufficient Funds |
Utilisez n'importe quelle date d'expiration future et n'importe quel CVC à 3 chiffres.
Application de démonstration
Une application de démonstration basée sur Docker est incluse dans le dépôt GitHub pour tester le flux de paiement complet.
Support
Besoin d'aide ? Contactez notre équipe de support à support@costplus.io.