This article describes all the steps needed to integrate the GoPay payment gateway in version V3 (REST API). You will find here everything you need to integrate online payments into your merchant outlet as quickly as possible.
For integration, the historical SOAP versions (V1, V2) cannot be used, because they have not been updated for a long time, do not support standard functionality, are associated with errors and require the use of outdated library versions and PHP versions before 8.1.
OAuth
The payment gateway interface uses the REST API for communication. Communication takes place using HTTPS requests. Access to the API is secured by the open secure protocol OAuth2.0.
The OAuth protocol makes it possible to obtain various levels of permission for accessing the individual API functions. Communication takes place on the basis of tokens. At the start of the integration you will receive the ClientID and ClientSecret values from us, which are used to create the tokens needed.
💡 GoPay tip:
If you have not received the ClientID and ClientSecret values yet, please contact us at [email protected].
The first step before creating a payment is therefore to create a token, which you then send with every API request. The token is passed in the header of the https request.
You obtain the token by calling the API at the URL /api/oauth2/token. The token can be created with two sets of permissions.
payment-create – creating payments and making payment status queries
payment-all – all other payment operations
The token obtained has a lifetime of 30 minutes and has to be passed in the header of every API request.
💡 GoPay tip:
The API for the test environment is at https://gw.sandbox.gopay.com/api/
The production environment is available at https://gate.gopay.cz/api/
Creating a payment
The next step for making a payment is to create it. The payment is created by a call to the URL /api/payments/payment of the GoPay REST API. When creating the payment, all its parameters are specified, such as the price, the payment currency, the allowed payment methods, the pre-selected payment method, the order items, the payment gateway language, the addresses for notifications and the addresses for returning to the merchant outlet. You will find more information in the description of a standard payment.
For the request to be successful, the previously created token authorising us to carry out the required operation has to be passed in the header.
The result of the call is a JSON object containing all the information about the payment. The most important of this information is the id parameter, which is the unique identifier of the payment in the GoPay system. The payment ID has to be saved in your database with the order the payment belongs to. The ID is used for subsequently processing the return from the payment gateway, or the http notification, successfully. Another important parameter is gw_url, which we will use in the next step to invoke the payment gateway.
Invoking the payment gateway
The payment gateway can be invoked either in the inline variant, where the payment takes place directly over the merchant's merchant outlet, or in the redirect variant, where the customer is redirected to the gopay.cz domain. You can test both of these methods in our demo shop https://www.goshop.cz. You can also choose between two ways of invoking the payment gateway – creating the payment in advance, or initialisation using JavaScript. Creating the payment in advance is more suitable for a multi-step basket, while initialisation using JavaScript is suitable for a single-confirmation payment.
Creating the payment in advance
This method is suitable for a multi-step basket, where, once the order is confirmed, the payment is created on the server and the customer is then shown a form pointing to gw_url to invoke the payment gateway, either in inline or redirect form. Once the form is submitted, the payment gateway is invoked.
Initialisation using JavaScript
The second method is to invoke the payment gateway using a JavaScript call. When the order is confirmed, an ajax request is made to your server. The server obtains a token and then creates the payment. As a response it returns the gw_url of the payment created. Once you have the gw_url, you invoke the payment gateway using the method:
_gopay.checkout({gatewayUrl: url, inline: true});
The method is parameterised by an object containing the gatewayUrl of the payment created and the inline parameter, which says whether the payment gateway will be invoked in the inline or redirect variant. To use the _gopay.checkout method you have to include the GoPay JavaScript API:
Test environment
<script type="text/javascript" src="https://gw.sandbox.gopay.com/gp-gw/js/embed.js">
Production environment
<script type="text/javascript" src="https://gate.gopay.cz/gp-gw/js/embed.js">
Below you will find an example of invoking the payment gateway using JavaScript:
<form id="payment-form" action="/create-payment" method="POST"> <label for="payment-amount">Částka: </label> <input type="number" name="amount" id="payment-amount" /> <button type="submit">Zaplatit Inline</button></form>
// Po odeslání formuláře dojde k asynchronnímu založení platby a následnému vyvolání inline bránydocument.addEventListener("DOMContentLoaded", () => { const paymentForm = document.querySelector("#payment-form"); paymentForm.addEventListener("submit", async (event) => { event.preventDefault(); const createResult = await createPayment(paymentForm); initInline(createResult); });}); // Asynchronní funkce pro vytvoření platby z formulářeconst createPayment = async (form) => { try { //serializace dat z formuláře jako JSON const formData = new FormData(form); const formObject = Object.fromEntries(formData.entries()); // Odeslání dat na endpoint, specifikovaný jako akce formuláře. const createResponse = await fetch(form.action, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(formObject) }); // Předpokládáme, že backend vrací JSON, který obsahuje popis platby z API odpovědi // viz https://doc.gopay.cz/#zalozeni-platby const createResult = await createResponse.json(); if (!createResponse.ok) { console.error( `Server returned: ${createResponse.status}: ${createResponse.statusText}:\n${createResult}` ); return; } return createResult; } catch (err) { console.error(err); }}; // Asynchronní funkce pro provedení dotazu na stav platby podle jejího IDconst getPaymentStatus = async (paymentId) => { try { // ID platby je v příkladu předáno jako query parametr "id". Upravte podle vašich potřeb. const statusResponse = await fetch(`/payment-status?id=${paymentId}`, { method: "GET", headers: { Accept: "application/json" } }); // Předpokládáme, že backend vrací JSON, který obsahuje popis platby z API odpovědi // viz https://doc.gopay.cz/#dotaz-na-stav-platby const paymentStatusResult = await statusResponse.json(); if (!statusResponse.ok) { console.error( `Server returned: ${statusResponse.status}: ${statusResponse.statusText}:\n${paymentStatus}` ); return; } return paymentStatusResult; } catch (err) { console.error(err); }}; // Funkce, pro vyvolání inline brányconst initInline = (createResult) => { try { // Vyvolání Inline brány prostřednictvím získané gw_url // Jako druhý parametr je předána callback funkce, která je volána při zavření brány _gopay.checkout({ gatewayUrl: createResult.gw_url, inline: true }, async (checkoutResult) => { // V objektu checkoutResult se nachází návratová URL, ID platby a její stav console.log(`Stav platby ${checkoutResult.id}: ${checkoutResult.state}`); // Pro další informace o platbě je možné zavolat dotaz na stav platby. const paymentStatusResult = await getPaymentStatus(checkoutResult.id); // A následně odpověď libovolně zpracovat console.log(paymentStatusResult); }); } catch (err) { console.error(err); }};
Returning from the payment gateway
Once the payment has been made or cancelled, the customer is returned to the merchant outlet. The return can be carried out in two ways. The first is a redirect to the return_url defined when creating the payment. The second option is to call a callback function passed as a further parameter to _gopay.checkout. In that case no redirect takes place. The callback function can only be invoked, however, in cases where the customer was not redirected outside the payment gateway to make the payment. Otherwise the standard redirect to return_url takes place.
Returning via the return URL
When creating the payment, the return_url parameter is passed in the callback object. Once the payment has been made, the customer is redirected to this URL. The payment gateway appends the GET parameter ?id=<payment_id> to the return_url. Using the id obtained you can easily identify which customer it is. You then have to use the id to make a payment status query and show the customer information about the current status.
Returning using a callback function
The second option is not to redirect to return_url. For payment methods where no redirect away from the payment gateway takes place (for example a card payment), the payment gateway can simply call a function you define and pass as part of invoking the payment gateway with _gopay.checkout. The call can therefore look as follows:
_gopay.checkout({gatewayUrl: inlineCreateResult.url, inline: true}, (checkoutResult) => {alert(checkoutResult);})
After the payment, the function you define will therefore be invoked. In the function we recommend making an ajax request to your server, which checks the payment status. On the basis of the payment status, show the customer the relevant information about the payment.
Even when using a callback function you have to allow for return_url. With some payment methods, for example online banking buttons, a redirect away from the payment gateway takes place and the callback function therefore cannot be invoked. In those cases the return is always to return_url.
Notifications
Notifications automatically inform the merchant outlet that the payment state has changed to one of the final states (PAID, CANCELED, TIMEOUTED, REFUNDED, PARTIALLY_REFUNDED).
The notification_url parameter is passed as part of the callback object when creating the payment. Whenever the payment state changes, we send an asynchronous HTTP/GET notification to this URL. The notification is called in the format http://eshop.tld?id=<payment_id>.
Using the GET parameter id you look up the relevant order in your database and make a payment status query, which tells you its current status. You save the status in the database with the order, or carry out the actions you have defined for the specific status, e.g. the payment being paid.
SSL certificate
To use the inline payment gateway at merchant outlets you need SSL (HTTPS support). At merchant outlets without an SSL certificate, the redirect variant described below is invoked by default.
The redirect variant is an alternative solution that takes the customer from the merchant outlet environment to the secure environment of the GoPay payment gateway. For smaller customers who are not in a position to obtain an SSL certificate, we recommend using this redirect variant of the payment gateway.
