Cost+Docs

Python

Opinbert Python SDK fyrir greiðslugátt Cost+

Opinbert Python SDK fyrir greiðslugátt Cost+. Poenostavlja tok preusmeritve HPP (gostovane greiðslune strani), HMAC podpisovanje koristnih podatkov og staðfesting webhook-ov.

Eiginleikar

  • Lágmarks dependency — aðeins requests
  • Polni type hints og zamrznjeni dataclass tipi vrnjenih vrednosti
  • HMAC-SHA256 býr tilnje podpisov og staðfesting með konstantnim časom
  • Razčlenjevanje webhook-ov + staðfesting pantana á osnovi API-ja
  • Prófað á Python 3.10, 3.11 og 3.12

Kröfur

Uppsetning

pip install nopayn-sdk

Flýtiræsing

1. Frumstilltu biðlarann

from nopayn import NoPaynClient

client = NoPaynClient(
    api_key="your-api-key",
    merchant_id="your-project",
)

2. Ustvarite greiðsla og preusmerite á HPP

result = client.generate_payment_url(
    amount=1295,             # €12.95 og 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",
)

# Preusmerite viðskiptavin
# result.order_url   → HPP (viðskiptavinur izbere greiðslumáta)
# result.payment_url → neposredna povezava do greiðslumátar prve transakcije
# result.signature   → HMAC-SHA256 til staðfesting
# result.order_id    → NoPayn UUID pantanir

3. Meðhöndlaðu webhook (primer Flask)

@app.route("/webhook", methods=["POST"])
def webhook():
    verified = client.verify_webhook(request.get_data(as_text=True))

    print(verified.order.status)  # 'completed', 'cancelled', etc.
    print(verified.is_final)      # True when the order won't change

    if verified.order.status == "completed":
        # Uppfylldu pöntunina
        pass

    return "", 200

API tilvísun

NoPaynClient(api_key, merchant_id, base_url?)

ParameterTipObveznoPrivzeto
api_keystrDa
merchant_idstrDa
base_urlstrNehttps://api.nopayn.co.uk

client.create_order(**kwargs) -> Order

Stofnar pöntun gegnum POST /v1/orders/.

ParameterTipObveznoOpis
amountintDaZnesek í najmanjši valutni enoti (centi)
currencystrDaKoda ISO 4217 (EUR, GBP, USD, NOK, SEK)
merchant_order_idstrNeVaša interna referenca pantanir
descriptionstrNeOpis pantanir
return_urlstrNePreusmeritev eftir uspešnem greiðsluu
failure_urlstrNePreusmeritev ob preklicu/poteku/napaki
webhook_urlstrNeAsinhrona obvestila o spremembi statusa
localestrNeJezik HPP (en-GB, de-DE, nl-NL itd.)
payment_methodslist[str]NeFiltriraj metode HPP
expiration_periodstrNeTrajanje ISO 8601 (PT30M)

Tiltækir greiðslumátar: credit-card, apple-pay, google-pay, vipps-mobilepay

client.get_order(order_id) -> Order

Sækir upplýsingar pöntunar gegnum GET /v1/orders/{id}/.

client.create_refund(order_id, amount, description?) -> Refund

Gefðu út fulla eða hluta endurgreiðslu gegnum POST /v1/orders/{id}/refunds/.

client.generate_payment_url(**kwargs) -> PaymentUrlResult

Þægileg aðferð, ki ustvari pöntun og vrne:

PaymentUrlResult(
    order_id="...",       # NoPayn UUID pantanir
    order_url="...",      # HPP URL
    payment_url="...",    # Neposredni greiðsluni URL (prva transakcija)
    signature="...",      # HMAC-SHA256 od amount:currency:order_id
    order=Order(...),     # Celoten objekt pantanir
)

client.generate_signature(amount, currency, order_id) -> str

Býr til HMAC-SHA256 šestnajstiški podpis.

client.verify_signature(amount, currency, order_id, signature) -> bool

Staðfesting HMAC-SHA256 podpisa með konstantnim časom.

client.verify_webhook(raw_body) -> VerifiedWebhook

Greinir telo webhook-a, nato poklief GET /v1/orders/{id}/ til staðfesting dejanskega statusa.

Sjálfstæð HMAC tól

from nopayn import generate_signature, verify_signature

sig = generate_signature("your-api-key", 1295, "EUR", "order-uuid")
ok = verify_signature("your-api-key", 1295, "EUR", "order-uuid", sig)

Gagnagerðir

Vsi API odgovori eru vrnjeni kot zamrznjeni dataclass objekti:

RazredPolja
Orderid, amount, currency, status, created, modified, transactions, description, merchant_order_id, return_url, failure_url, order_url, completed
Transactionid, amount, currency, status, created, modified, payment_method, payment_url, expiration_period
Refundid, amount, status
PaymentUrlResultorder_id, order_url, payment_url, signature, order
VerifiedWebhookorder_id, order, is_final

Villum meðhöndlun

from nopayn import ApiError, NoPaynError, WebhookError

try:
    client.create_order(amount=100, currency="EUR")
except ApiError as exc:
    print(exc.status_code)  # 401, 400, etc.
    print(exc.error_body)   # Raw API error response
except NoPaynError as exc:
    print(exc)              # Network or parsing error

Statusi pantana

StatusKončni?Opis
newNePöntun ustvarjeno
processingNeGreiðsla í teku
completedDaGreiðsla uspešno — dostavite blago
cancelledDaGreiðsla preklicano með strani viðskiptavinar
expiredDaPlačilna povezava er potekla
errorDaTehnična napaka

Bestu venjur fyrir webhook-a

  1. Vedno preverite gegnum API-ja — koristni podatki webhook-a vsebujejo aðeins ID pantanir, nikoli statusa. SDK-jev verify_webhook() to naredi samodejno.
  2. Vrnite HTTP 200 til potrditev prejema. Katerakoli druga koda sproži do 10 ponovnih poskusov (2 minuti narazen).
  3. Implementirajte rezervno poizvedovanje — til pantanir, starejša od 10 minut, ki še niso dosegla končnega statusa, poizvedujte get_order() kot varnostno mrežo.
  4. Vertu idempotent — isti webhook lahþegar prejmete večkrat.

Prófunarkort

Uporabite te kartice í testnem načinu Cost+ (vefsíðu sandboxa):

KarticaŠtevilkaOpombe
Visa (uspeh)4111 1111 1111 1111Katerikoli CVV
Mastercard (uspeh)5544 3300 0003 7Katerikoli CVV
Visa (zavrnjena)4111 1111 1111 1105Zavrnitev
Visa (nezadostna sredstva)4111 1111 1111 1151Nezadostna sredstva

Uporabite katerikoli prihodnji datum veljavnosti og katerokoli 3-mestno CVC kodo.

Sýnisforrit

Sýnisforrit á osnovi Flask er vključena í GitHub repozitorij til testiranje celotnega greiðslunega toka.

Aðstoð

Þarftu aðstoð? Hafðu samband við þjónustudeild okkar á support@costplus.io.

On this page