GoPay's Python SDK for Payments REST API
Requirements
- Python >= 3.8.1
- dependencies:
Installation
The simplest way to install SDK is to use PIP:
pip install gopay
Basic usage
import gopay
from gopay.enums import TokenScope, Language
payments = gopay.payments({
"goid": "{{YOUR-GOID}}",
"client_id": "{{YOUR-CLIENT-ID}}",
"client_secret": "{{YOUR-CLIENT-SECRET}}",
"gateway_url": 'https://gw.sandbox.gopay.com/api'
})
payments = gopay.payments({
"goid": "{{YOUR-GOID}}",
"client_id": "{{YOUR-CLIENT-ID}}",
"client_secret": "{{YOUR-CLIENT-SECRET}}",
"gateway_url": 'https://gw.sandbox.gopay.com/api'
"scope": TokenScope.ALL,
"language": Language.CZECH
})
Configuration
Required fields
Required field | Data type | Documentation |
---|
goid | string | GoID assigned by GoPay (production or sandbox) |
client_id | string | Client ID assigned by GoPay (production or sandbox) |
client_secret | string | Client Secret assigned by GoPay (production or sandbox) |
gateway_url | string | URL of the environment - production or sandbox (see Docs) |
Optional fields
Available methods
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"]
else:
print(f"Oops, API returned {response.status_code}: {response}")
Property/Method | Description |
---|
response.success | Checks if API call was successful |
response.json | decoded response, returned objects are converted into a dictionary if possiblem |
response.status_code | HTTP status code |
response.raw_body | raw 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 doc.gopay.com.
In the future, we might use Pydantic for parsing and validation.
Advanced usage
Initiation of the payment gateway
response = payments.create_payment(...)
if response.has_succeed():
context = {
'gateway_url': response.json['gw_url'],
'embedjs_url': payments.get_embedjs_url
}
<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>
</form>
<form action="{{ gateway_url }}" method="post">
<button name="pay" type="submit">Pay</button>
</form>
Instead of hardcoding bank codes string you can use predefined enums.
Check using enums in create-payment example
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 gopay.services.DefaultCache
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 gopay.services.AbstractCache
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 gopay.services 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)
def set_token(self, key: str, token: AccessToken) -> None:
self.tokens[key] = token
payments = gopay.payments(
{...},
{"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: ...
Callable[[gopay.http.Response, gopay.http.Request], Any]
For example:
from gopay.http import Request, Response
def my_logger(request: Request, response: Response) -> None:
print(vars(request))
print(vars(response))
payments = gopay.payments(
{...},
{"logger": my_logger}
)
The default logger uses logging.debug
to log the responses and requests.
Contributing
Contributions from others would be very much appreciated! Send
pull request/
issue. Thanks!
License
Copyright (c) 2023 GoPay.com. MIT Licensed,
see LICENSE for details.