Sign inDemoInstall


Package Overview
File Explorer

Install Socket

Protect your apps from supply chain attacks



GoPay's Python SDK for Payments REST API




GoPay's Python SDK for Payments REST API

Build Status



The simplest way to install SDK is to use PIP:

pip install gopay

Basic usage

import gopay
from gopay.enums import TokenScope, Language

# minimal configuration
payments = gopay.payments({
    "goid": "{{YOUR-GOID}}",
    "client_id": "{{YOUR-CLIENT-ID}}",
    "client_secret": "{{YOUR-CLIENT-SECRET}}",
    "gateway_url": ''

# full configuration
payments = gopay.payments({
    "goid": "{{YOUR-GOID}}",
    "client_id": "{{YOUR-CLIENT-ID}}",
    "client_secret": "{{YOUR-CLIENT-SECRET}}",
    "gateway_url": ''
    "scope": TokenScope.ALL,
    "language": Language.CZECH

# Sandbox URL:
# Production URL:


Required fields
Required fieldData typeDocumentation
goidstringGoID assigned by GoPay (production or sandbox)
client_idstringClient ID assigned by GoPay (production or sandbox)
client_secretstringClient Secret assigned by GoPay (production or sandbox)
gateway_urlstringURL of the environment - production or sandbox (see Docs)
Optional fields
Optional fieldData typeDefault valueDocumentation
languagestringgopay.enums.Language.ENGLISHdefault language to use + localization of errors

Available methods

APISDK method
Create a paymentpayments.create_payment(payment: dict)
Get status of a paymentpayments.get_status(payment_id: str | int)
Refund a paymentpayments.refund_payment(payment_id: int | str, amount: int)
Create a recurring paymentpayments.create_recurrence(payment_id: int | str, payment: dict)
Cancel a recurring paymentpayments.void_recurrence(payment_id: int | str)
Capture a preauthorized paymentpayments.capture_authorization(payment_id: int | str)
Capture a preauthorized payment partiallypayments.capture_authorization_partial(payment_id: int | str, payment: dict)
Void a preauthorized paymentpayments.void_authorization(payment_id: int | str)
Get payment card detailspayments.get_card_details(card_id: int | str)
Delete a saved cardpayments.delete_card(card_id: int | str)
Get allowed payment methods for a currencypayments.get_payment_instruments(goid: int | str, currency: gopay.enums.Currency)
Get all allowed payment methodspayments.get_payment_instruments_all(goid: int | str)
Generate an account statementpayments.get_account_statement(statement_request: dict)

SDK response? Has my call succeed?

SDK returns wrapped API response. Every method returns gopay.http.Response object. Structure of the json should be same as in documentation. SDK throws no exception. Please create an issue if you catch one.

response = payments.create_payment(...)
if response.success:
    print(f"Hooray, API returned {response}")
    return response.json["gw_url"] # url for initiation of gateway
    # errors format:
    print(f"Oops, API returned  {response.status_code}: {response}")
response.successChecks if API call was successful
response.jsondecoded response, returned objects are converted into a dictionary if possiblem
response.status_codeHTTP status code
response.raw_bodyraw bytes of the reponse content

Are required fields and allowed values validated?

Not yet. API validates fields pretty extensively so there is no need to duplicate validation in SDK. That's why SDK just calls API which behavior is well documented in In the future, we might use Pydantic for parsing and validation.

Advanced usage

Initiation of the payment gateway

# create payment and pass url to template (e.g. Flask, Django)
response = payments.create_payment(...)
if response.has_succeed():
    context = {
        'gateway_url': response.json['gw_url'],
        'embedjs_url': payments.get_embedjs_url
    # render template
Inline gateway
<form action="{{ gateway_url }}" method="post" id="gopay-payment-button">
  <button name="pay" type="submit">Pay</button>
  <script type="text/javascript" src="{{ embedjs_url }}"></script>
Redirect gateway
<form action="{{ gateway_url }}" method="post">
  <button name="pay" type="submit">Pay</button>
Asynchronous initialization using JavaScript


Instead of hardcoding bank codes string you can use predefined enums. Check using enums in create-payment example

LanguagePayment language, localization of error messages
Token scopeAuthorization scope for OAuth2
Payment enumsEnums for creating payment
Response enumsResult of creating payment, executing payment operations

Cache access token

Access token expires after 30 minutes it's expensive to use new token for every request. By default, tokens are stored in memory so they are reused as long as the object exists. But you can implement your cache and store tokens in Memcache, Redis, files, ... It's up to you.

Your cache should inherit from and implement its methods get_token and set_token. Be aware that there are two scopes (TokenScope) and SDK can be used for different clients (client_id, gateway_url). So key passed to methods is unique identifier (str) that is built for current environment. Below you can see example implementation of caching tokens in memory:

from import AbstractCache
from gopay.http import AccessToken

class MyCache(AbstractCache):
    def __init__(self):
        self.tokens: dict[str, AccessToken] = {}

    def get_token(self, key: str) -> AccessToken | None:
        return self.tokens.get(key) # return None if token doesn't exist

    def set_token(self, key: str, token: AccessToken) -> None:
        self.tokens[key] = token

# register cache in optional service configuration
payments = gopay.payments(
    {...}, # your config
    {"cache": MyCache()}

Log HTTP communication

You can log every request and response from communication with API. Check available loggers below. Or you can implement your own logger, just implement function that matches the following signature:

def logger(gopay.http.Request, gopay.http.Response) -> Any: ...
# or
Callable[[gopay.http.Response, gopay.http.Request], Any]

For example:

from gopay.http import Request, Response

def my_logger(request: Request, response: Response) -> None:

# register logger in optional service configuration
payments = gopay.payments(
    {...}, # your config
    {"logger": my_logger}

The default logger uses logging.debug to log the responses and requests.


Contributions from others would be very much appreciated! Send pull request/ issue. Thanks!


Copyright (c) 2023 MIT Licensed, see LICENSE for details.



Did you know?

Socket installs a GitHub app to automatically flag issues on every pull request and report the health of your dependencies. Find out what is inside your node modules and prevent malicious activity before you update the dependencies.


Related posts

SocketSocket SOC 2 Logo


  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc