Ruby
SDK ufficiale Ruby per il gateway di pagamento Cost+
SDK ufficiale Ruby 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
- Generazione firma HMAC-SHA256 e verifica a tempo costante
- Mappatura automatica snake_case dall'API a oggetti OpenStruct Ruby-friendly
- Analisi webhook + verifica dell'ordine basata su API
- Testato su Ruby 3.1, 3.2 e 3.3
- App demo merchant basata su Sinatra inclusa
Requisiti
- Ruby 3.1 o successivo
- Un account commerciante Cost+ — dashboard.costplus.io
Installazione
Aggiungi al tuo Gemfile:
gem "nopayn"Poi esegui:
bundle installOppure installa direttamente:
gem install nopaynGuida Rapida
1. Inizializza il Client
require "nopayn"
nopayn = NoPayn::Client.new(
api_key: "your-api-key",
merchant_id: "your-project"
)2. Crea un Pagamento e Reindirizza all'HPP
result = nopayn.generate_payment_url(
amount: 1295, # €12.95 in cents
currency: "EUR",
merchant_order_id: "ORDER-001",
description: "Premium Widget",
return_url: "https://shop.example.com/success",
failure_url: "https://shop.example.com/failure",
webhook_url: "https://shop.example.com/webhook",
locale: "en-GB",
expiration_period: "PT30M"
)
# Redirect the customer
# result.order_url → HPP (customer picks payment method)
# result.payment_url → direct link to the first transaction's payment method
# result.signature → HMAC-SHA256 for verification
# result.order_id → NoPayn order UUID3. Gestisci il Webhook
post "/webhook" do
request.body.rewind
raw_body = request.body.read
verified = nopayn.verify_webhook(raw_body)
puts verified.order.status # "completed", "cancelled", etc.
puts verified.is_final # true when the order won't change
if verified.order.status == "completed"
# Fulfil the order
end
status 200
endRiferimento API
NoPayn::Client.new(api_key:, merchant_id:, base_url:)
| Parametro | Tipo | Obbligatorio | Predefinito |
|---|---|---|---|
api_key | String | Sì | — |
merchant_id | String | Sì | — |
base_url | String | No | https://api.nopayn.co.uk |
client.create_order(params) → OpenStruct
Crea un ordine tramite POST /v1/orders/.
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
:amount | Integer | Sì | Importo nell'unità valutaria più piccola (centesimi) |
:currency | String | Sì | Codice ISO 4217 (EUR, GBP, USD, NOK, SEK) |
:merchant_order_id | String | No | Il tuo riferimento interno dell'ordine |
:description | String | No | Descrizione dell'ordine |
:return_url | String | No | Reindirizzamento dopo pagamento riuscito |
:failure_url | String | No | Reindirizzamento in caso di annullamento/scadenza/errore |
:webhook_url | String | No | Notifiche asincrone di cambio stato |
:locale | String | No | Lingua HPP (en-GB, de-DE, nl-NL, ecc.) |
:payment_methods | Array<String> | No | Filtra i metodi HPP |
:expiration_period | String | No | Durata ISO 8601 (PT30M) |
Metodi di pagamento disponibili: credit-card, apple-pay, google-pay, vipps-mobilepay
client.get_order(order_id) → OpenStruct
Recupera i dettagli dell'ordine tramite GET /v1/orders/{id}/.
client.create_refund(order_id, amount, description: nil) → OpenStruct
Emette un rimborso totale o parziale tramite POST /v1/orders/{id}/refunds/.
client.generate_payment_url(params) → OpenStruct
Metodo di convenienza che crea un ordine e restituisce:
result.order_id # NoPayn order UUID
result.order_url # HPP URL
result.payment_url # Direct payment URL (first transaction)
result.signature # HMAC-SHA256 of amount:currency:order_id
result.order # Full order OpenStructclient.generate_signature(amount, currency, order_id) → String
Genera una firma HMAC-SHA256 esadecimale.
client.verify_signature(amount, currency, order_id, signature) → Boolean
Verifica a tempo costante di una firma HMAC-SHA256.
client.verify_webhook(raw_body) → OpenStruct
Analizza il corpo del webhook, poi chiama GET /v1/orders/{id}/ per verificare lo stato effettivo.
Utility HMAC Standalone
require "nopayn"
sig = NoPayn::Signature.generate("your-api-key", 1295, "EUR", "order-uuid")
ok = NoPayn::Signature.verify("your-api-key", 1295, "EUR", "order-uuid", sig)Gestione degli Errori
begin
nopayn.create_order(amount: 100, currency: "EUR")
rescue NoPayn::ApiError => e
puts e.status_code # 401, 400, etc.
puts e.error_body # Raw API error response
rescue NoPayn::Error => e
puts e.message # Network or parsing error
end| Eccezione | Classe Padre | Descrizione |
|---|---|---|
NoPayn::Error | StandardError | Errore base per tutti gli errori dell'SDK |
NoPayn::ApiError | NoPayn::Error | Errore HTTP dall'API |
NoPayn::WebhookError | NoPayn::Error | Payload webhook non valido |
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
verify_webhookdell'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
get_ordercome 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 Sinatra è 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.