Cost+Docs

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/sdk

Dé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ètreTypeObligatoirePar défaut
apiKeystringOui
merchantIdstringOui
baseUrlstringNonhttps://api.nopayn.co.uk

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

Crée une commande via POST /v1/orders/.

ParamètreTypeObligatoireDescription
amountintOuiMontant dans la plus petite unité monétaire (centimes)
currencystringOuiCode ISO 4217 (EUR, GBP, USD, NOK, SEK)
merchantOrderIdstringNonVotre référence interne de commande
descriptionstringNonDescription de la commande
returnUrlstringNonRedirection après paiement réussi
failureUrlstringNonRedirection en cas d'annulation/expiration/erreur
webhookUrlstringNonNotifications asynchrones de changement de statut
localestringNonLangue de la HPP (en-GB, de-DE, nl-NL, etc.)
paymentMethodsstring[]NonFiltrer les méthodes HPP
expirationPeriodstringNonDuré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

StatutFinal ?Description
newNonCommande créée
processingNonPaiement en cours
completedOuiPaiement réussi — livrez les marchandises
cancelledOuiPaiement annulé par le client
expiredOuiLe lien de paiement a expiré
errorOuiErreur technique

Bonnes pratiques pour les webhooks

  1. 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.
  2. Renvoyez HTTP 200 pour accuser réception. Tout autre code déclenche jusqu'à 10 tentatives (espacées de 2 minutes).
  3. 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é.
  4. Soyez idempotent — vous pouvez recevoir le même webhook plusieurs fois.

Cartes de test

Utilisez ces cartes en mode test Cost+ (site web sandbox) :

CarteNuméroNotes
Visa (succès)4111 1111 1111 1111N'importe quel CVV
Mastercard (succès)5544 3300 0003 7N'importe quel CVV
Visa (refusée)4111 1111 1111 1105Do Not Honor
Visa (fonds insuffisants)4111 1111 1111 1151Insufficient 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.

On this page