Download the PHP package gopaycommunity/gopay-php-api-v4 without Composer

On this page you can find all versions of the php package gopaycommunity/gopay-php-api-v4. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package gopay-php-api-v4

GoPay PHP SDK — Payments API v4

Packagist Version PHP Version License Quality Gate Status Coverage

Server-side PHP SDK for new GoPay Payments API v4.

Requires PHP ≥ 8.1. Transport-agnostic — works with any PSR-18 HTTP client.


v3 → v4 migration

See MIGRATION.md for a full breakdown. The SDK is v4-only — not source-level compatible with gopay/payments-sdk v1.

Key changes:


Installation

For the HTTP client you need a PSR-18 implementation. Guzzle 7 is the most common choice:

Any PSR-18-compatible client works (Symfony HttpClient, Buzz, …).


Quick start

ip, user_agent and accept_header must come from the customer's browser. The browser calls GET /cards/browser-data (authenticated with client_id:shareable_key) immediately before the charge; the response carries all three, and your server merges them into browser_data. The endpoint reports whatever fetched it, so a call from your own server returns the server's address and headers — which the issuer rejects during 3-D Secure. That is why the SDK exposes no method for it: from PHP it would produce exactly the wrong values.

Reading them off the incoming request instead is not the way round it. The Accept headers there do belong to the customer, but ip does not survive a proxy, and the contract wants all three from one observation rather than a mix of two sources.

gw_url — GoPay's hosted payment gateway. The PaymentDetails object contains a gw_url field: the address of GoPay's hosted gateway for this payment, which offers the customer every payment method the eshop has enabled and drives the payment while the customer is on it. It is a destination the customer is sent to — it cannot be embedded in your own checkout, and that, not a missing payment method, is the reason not to redirect there by default. Driving the payment inside your own UI is what this SDK's flow (createPayment() → chargePayment()) is for; that checkout integration today covers card, Google Pay, Apple Pay and QR payments and is being extended to further methods, while the gateway already offers every method the eshop has enabled. Either way the payment stays fully v4-observable: getPaymentStatus() reports the final state once the customer completes it, exactly as it would for a payment charged directly through v4. Drive one or the other for a given payment attempt, never both.


Configuration

Parameter Type Default Description
environment Environment Sandbox API environment
baseUrl ?string null Override the resolved URL (e.g. for staging)
debugLoggingEnabled bool false Log to error_log
onError ?callable null Invoked before every thrown exception
shareableKey ?string null Shareable key for getBrowserKeys()

Environments

Environment Base URL
Environment::Sandbox https://gw.sandbox.gopay.com/gp-gw/api/4.0
Environment::Production https://gate.gopay.com/gp-gw/api/4.0

PSR-18 HTTP client injection

By default, php-http/discovery auto-discovers an installed PSR-18 client. You can inject your own:


API reference

Authentication

Payments

Cards

Refunds

Server-side only — refundPayment needs the payment:write scope, which a payment-scoped browser token never carries.

A FAILED refund is returned rather than raised — unlike awaitChargeState(), which raises on failure. The refundable amount is untouched, so the caller decides whether to retry.

amount is in minor units and must be positive — the API rejects 0 and negative values with 400.

A card payment can only be refunded in full at first; a partial refund attempted too early is rejected with 409. This is not in the OpenAPI spec — it is the gateway's own rejection, reproduced against the sandbox, which words it as:

Partial refund is not allowed for this payment; only a full refund is possible (e.g. a card payment before settlement can only be fully reversed)

RefundDetails carries id, state, amount, currency, created_at and updated_at. It has no payment_id and no failure reason — the gateway does not return them, so keep your own mapping if you need to resolve a refund back to its payment.


Payment links

A payment link lets you collect a payment without an integration: you create the link, share its url, and the payment is created when the customer opens it. Server-side only — creating and disabling a link need the payment:write scope, reading one needs payment:read.

id and url are two different identifiers and neither can be derived from the other: id is the numeric link ID used by this API, while url ends in a random ten-character code that is the only thing protecting the link.

A reusable link (the default) creates a new payment on every visit — and every one of them carries the same order_number and the same notification_url, so your shop can receive notifications for several payments that all look like one order. Check that it tolerates this before sharing a reusable link.

A one-shot link (reusable => false) is consumed by the first visit and then keeps redirecting to the payment it created, so a customer who refreshes or comes back later still reaches their payment. It cannot be disabled afterwards — disableLink() answers 409, because the link is already inactive. To stop that payment, cancel the payment itself.

Expiry is evaluated on read: once a link is past its expires_at, linkStatus() reports active: false with stop reason EXPIRED without anything being written first.

LinkDetails carries id, url, active, reusable, and — once the link is no longer active — stop_reason (FROM_API, USED or EXPIRED). While the link is active, getStopReason() returns null. A link that belongs to another eshop answers 404, not 403, so the response does not reveal whether it exists.


Recurrences

A recurrence holds a payment template and creates payments from it. In v4 it is a standalone entity with its own ID — not something attached to an existing payment, the way v3's createRecurrence($paymentId, …) was. Server-side only: every operation except reading needs the payment:write scope, which a payment-scoped browser token never carries.

Two kinds

The create body is a discriminated union on type, and the variants differ by more than that one field. An AUTO recurrence carries a schedule and GoPay creates the payments itself; an ON_DEMAND one must not carry a schedule, because you ask for each further payment with recurrenceNext().

recurrence_date_to is required for both and is the last day the recurrence may create a payment, as a plain yyyy-MM-dd date — a value carrying a time is rejected with 400. It belongs at the top level, never inside schedule. Both variants are additionalProperties: false, so an unknown field at any level, including inside payment.customer, is a 400 rather than something the server quietly drops.

The lifecycle, and the state names that do not match it

startRecurrence() creates the first payment and moves the recurrence to REQUESTED, not STARTED. It becomes STARTED only once the customer has actually paid that first payment. For the whole window in between, recurrenceNext() answers 409 — so code that starts a recurrence and immediately asks for the next payment gets a conflict, not a payment. Calling startRecurrence() again while the first payment is in flight also answers 409.

Per-payment overrides

startRecurrence() and recurrenceNext() both take an optional body that overrides the stored template for that one payment: amount, order_number, order_description, additional_params, customer and callback.

customer is merged field by field rather than replaced, so a partial one is fine — it may omit email, even though the shared Customer schema requires one. An unknown field anywhere in the override is a 400.

An empty nested object needs (object) [], not []. PHP cannot tell an empty map from an empty list, so ['customer' => []] is encoded as {"customer":[]} and the gateway answers 400 — Cannot deserialize value of type Customer from Array value. The SDK coerces the top level of a request body to an object for you, so startRecurrence($id, []) is fine, but it deliberately stops there: coercing recursively would turn a legitimately empty list such as additional_params into {}. Where you genuinely want an empty object, say so:

In practice an empty customer overrides nothing, so omitting the key entirely is usually what you want.

Stopping

stopRecurrence() answers 204 and moves the recurrence to STOPPED with stop_reason CANCELLED_VIA_API. It cannot be undone: a second stop answers 409, and so does starting a stopped recurrence. Payments the recurrence already created are unaffected — cancel or refund those individually.

RecurrenceDetails carries id, type, state, recurrence_date_to, payment, plus schedule for an AUTO recurrence and stop_reason once it is STOPPED (RECURRENCE_EXPIRED, CARD_EXPIRED, CANCELLED_VIA_API, CANCELLED_VIA_BACKOFFICE, CANCELLED_BY_GOPAY or UNKNOWN). While it is still running, getStopReason() returns null.

getPayment() returns a RecurrencePayment, not a PaymentDetails. Before the recurrence is started it is the stored template, so id, state, gw_url and payment_secret are all null and only fill in once a payment exists.

A recurrence ID that is well-formed but does not exist answers 404; one that is not a valid ID at all answers 400.

RecurrenceState::_NEW, with an underscore. new is a reserved word in PHP, so the generated constant for the NEW state is _NEW. Only the PHP constant is affected — the value on the wire is the plain string NEW.


Response objects

All API methods return typed objects. Use the provided getters to access fields:

Charge flow for 3DS cards

The charge runs asynchronously. The response to chargePayment() is usually still PROCESSING, and a 3DS challenge rarely shows up in it — it usually appears when you poll GET /payments/{id}/charge a moment later. So poll straight after the POST until the charge reaches SUCCEEDED, FAILED or ACTION_REQUIRED, and redirect on ACTION_REQUIRED at once:

Only SUCCEEDED means the charge went through: ACTION_REQUIRED is returned, not raised, and is not paid. It is returned only while the customer still has a 3DS step to do and the action carries its redirect URL; once that step is over, awaitChargeState() keeps polling until the charge succeeds or fails. Don't wait for a webhook instead of polling: none is sent for a 3DS challenge, so a customer whose card wants one is never redirected.

Redirect to the 3DS URL immediately. The redirect URL opens an authentication session held open by the customer's bank, and that session has a short timeout on the bank's side. If the customer does not arrive in time, the bank cancels the authentication and the payment fails — there is nothing the SDK or GoPay can do about it, and retrying means starting a new payment.

So getRedirectUrl() must be followed by the redirect and nothing else. Do not put work between the two:

  • no order bookkeeping, database writes, invoice generation or stock reservations
  • no confirmation emails or other outbound calls (an unreachable SMTP host alone can burn the window)
  • no "please wait, redirecting…" interstitial, and no meta-refresh or JavaScript timer
  • no handing the URL to a queue, cron or background job to open later
  • no storing it to reuse on a later request — the URL is good for this one attempt, now

All of that belongs after the customer comes back, in your return_url handler or — better, because it does not depend on the customer's browser returning at all — in the webhook delivered to notification_url. See Polling payment state after a redirect.

Polling payment state after a redirect

After 3DS the customer is redirected to your return_url. At that point use getPaymentStatus() and PaymentPoller to determine the outcome:

PaymentPoller groups payment states into three buckets:

Group States Meaning
Pending CREATED, PAYMENT_METHOD_CHOSEN Still in progress — keep polling
Successful PAID, AUTHORIZED Completed successfully
Failed CANCELED, TIMEOUTED Did not complete

Post-success states (REFUNDED, PARTIALLY_REFUNDED) are terminal — isTerminal() returns true for them.


QR payment flow


Error handling

All SDK methods throw on error:

Exception When
GoPaySdkException Config errors, auth failures, timeout, argument errors
GoPayHttpException Non-2xx API responses (status + body available)

Error codes (ErrorCode enum)

Code Meaning
AuthTokenMissing No token; call authenticate() first
AuthRefreshFailed Token refresh HTTP error
AuthInvalidResponse Token response missing required fields
AuthCredentialsMissing No stored client credentials
AuthUnauthorized Still 401 after token refresh
NetworkError Transport-level failure, including timeouts
ChargeTimeout awaitChargeState() or awaitRefundState() timed out
ChargeFailed Charge reached FAILED state
UnexpectedResponse API responded with an unexpected body shape
InvalidConfig Bad configuration
InvalidArgument Empty required argument

onError callback


Production deployment

Token caching

GoPayClient stores the OAuth2 access token in memory inside a single instance. In conventional PHP-FPM / mod_php deployments each HTTP request is a new process, so every new GoPayClient(...) + authenticate() call makes a fresh round-trip to the GoPay token endpoint (typically 50–200 ms).

Tokens are valid for several minutes. To avoid re-fetching on every request, store the raw token in a shared cache (APCu, Redis, Memcached) and restore it before making API calls:

A first-class TokenCacheInterface (injectable into Config) is planned for a future release. Until then, the pattern above or a singleton per worker process is the recommended approach.

awaitChargeState / awaitRefundState in web contexts

awaitChargeState() and awaitRefundState() both usleep() in a loop and block the PHP worker process until the state is decided — at most $timeoutSeconds (default 30 s). Under concurrent load this can exhaust the worker pool.

Charges: poll in the request that charged. The 3DS redirect URL only becomes known by polling, and the customer has to be sent there while the bank's authentication session is still open, so awaitChargeState() belongs in the same request as chargePayment(). It returns as soon as the charge succeeds or asks for 3DS — usually within a few seconds. Size the worker pool for that, rather than moving the poll to a webhook: no notification is sent for a 3DS challenge.

Refunds and the final payment outcome: prefer the webhook-driven pattern for production web servers:

  1. GoPay POSTs a notification to your notification_url.
  2. Your handler calls getPaymentStatus() — or getRefund() for a refund — once and records the result.
  3. Return HTTP 200 immediately.

Use awaitRefundState() only in CLI scripts or environments with ample worker headroom.


Browser SDK compatibility

The PHP SDK handles the server side; the GoPay browser SDK handles the card form in an iframe.

  1. Browser: mountCardForm() → user enters card → iframe submits → returns { token, card_id }.
  2. Server: chargePayment($paymentId, ['payment_instrument' => ['payment_instrument' => 'PAYMENT_CARD', 'input' => ['input_type' => 'CARD_TOKEN', 'card_token' => $token]]]).

For browser SDK initialisation, pass the result of getBrowserKeys() to the page:

JWE tokenization flow (return-payload mode)

When the iframe is configured in return-payload mode, it returns a JWE compact serialization string instead of calling /cards/tokens itself. Forward it from the browser to your server, then exchange it for a permanent token:


Examples

Runnable scripts in examples/ demonstrate the full payment flow against the GoPay sandbox. See examples/README.md for setup and usage.


Development

Regenerating model classes

The PHP model classes in src/Generated/ are auto-generated from the GoPay OpenAPI spec. To regenerate them:

This reads the spec from SPEC_SOURCE (a URL or a local path — see scripts/codegen.sh), strips the mock server entry the feed injects, runs the OpenAPI generator in Docker, and copies the output into src/Generated/. Review the diff before committing — in particular check that the namespace (GoPay\Payments\Generated\Model) and ModelInterface compatibility are preserved.

Do not edit files in src/Generated/ by hand. If a model class is wrong, fix the upstream spec.


License

MIT


All versions of gopay-php-api-v4 with dependencies

PHP Build Version
Package Version
Requires php Version >=8.1
psr/http-client Version ^1.0
psr/http-factory Version ^1.0
psr/http-message Version ^1.0 || ^2.0
php-http/discovery Version ^1.14
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package gopaycommunity/gopay-php-api-v4 contains the following files

Loading the files please wait ...