# GoPay's Python SDK for Payments REST API
[![Build Status](https://travis-ci.org/gopaycommunity/gopay-python-api.svg?branch=master)](https://travis-ci.org/gopaycommunity/gopay-python-api)
## Requirements
- Python >= 3.8.1
- dependencies:
- [`requests`](https://github.com/kennethreitz/requests)
- [`deprecated`](https://github.com/tantale/deprecated)
## Installation
The simplest way to install SDK is to use [PIP](https://docs.python.org/3/installing/):
```bash
pip install gopay
```
## Basic usage
```python
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": 'https://gw.sandbox.gopay.com/api'
})
# full configuration
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
})
# Sandbox URL: https://gw.sandbox.gopay.com/api
# Production URL: https://gate.gopay.cz/api
```
### 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](https://doc.gopay.com)) |
#### Optional fields
Optional field | Data type | Default value | Documentation |
-------------- | --------- | ------------- | ------------- |
`scope` | string | [`gopay.enums.TokenScope.ALL`](gopay/enums.py) | <https://doc.gopay.com/#access-token> |
`language` | string | [`gopay.enums.Language.ENGLISH`](gopay/enums.py) | default language to use + [localization of errors](https://doc.gopay.com/#error)
### Available methods
API | SDK method |
--- | ---------- |
[Create a payment](https://doc.gopay.com#payment-creation) | `payments.create_payment(payment: dict)` |
[Get status of a payment](https://doc.gopay.com#payment-inquiry) | `payments.get_status(payment_id: str \| int)` |
[Refund a payment](https://doc.gopay.com#payment-refund) | `payments.refund_payment(payment_id: int \| str, amount: int)` |
[Create a recurring payment](https://doc.gopay.com#creating-a-recurrence) | `payments.create_recurrence(payment_id: int \| str, payment: dict)` |
[Cancel a recurring payment](https://doc.gopay.com#void-a-recurring-payment) | `payments.void_recurrence(payment_id: int \| str)` |
[Capture a preauthorized payment](https://doc.gopay.com#capturing-a-preauthorized-payment) | `payments.capture_authorization(payment_id: int \| str)` |
[Capture a preauthorized payment partially](https://doc.gopay.com#partially-capturing-a-preauthorized-payment) | `payments.capture_authorization_partial(payment_id: int \| str, payment: dict)` |
[Void a preauthorized payment](https://doc.gopay.com#voiding-a-preauthorized-payment) | `payments.void_authorization(payment_id: int \| str)` |
[Get payment card details](https://doc.gopay.com#payment-card-inquiry) | `payments.get_card_details(card_id: int \| str)` |
[Delete a saved card](https://doc.gopay.com#payment-card-deletion) | `payments.delete_card(card_id: int \| str)` |
[Get allowed payment methods for a currency](https://doc.gopay.com#available-payment-methods-for-a-currency) | `payments.get_payment_instruments(goid: int \| str, currency: gopay.enums.Currency)` |
[Get all allowed payment methods](https://doc.gopay.com#all-available-payment-methods) | `payments.get_payment_instruments_all(goid: int \| str)` |
[Generate an account statement](https://doc.gopay.com#account-statement) | `payments.get_account_statement(statement_request: dict)`
### SDK response? Has my call succeed?
SDK returns wrapped API response. Every method returns
[`gopay.http.Response` object](gopay/http.py). Structure of the `json`
should be same as in [documentation](https://doc.gopay.com).
SDK throws no exception. Please create an issue if you catch one.
```python
response = payments.create_payment(...)
if response.success:
print(f"Hooray, API returned {response}")
return response.json["gw_url"] # url for initiation of gateway
else:
# errors format: https://doc.gopay.com#HTTP-result-codes
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](https://doc.gopay.com/#error) 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](https://doc.gopay.com).
In the future, we might use Pydantic for parsing and validation.
*****
## Advanced usage
### Initiation of the payment gateway
```python
# 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](https://doc.gopay.com#inline)
```jinja
<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>
```
#### [Redirect gateway](https://doc.gopay.com#redirect)
```jinja
<form action="{{ gateway_url }}" method="post">
<button name="pay" type="submit">Pay</button>
</form>
```
#### [Asynchronous initialization using JavaScript](https://doc.gopay.com#inline)
### [Enums](https://doc.gopay.com#enums)
Instead of hardcoding bank codes string you can use predefined enums.
Check using enums in [create-payment example](/examples/create_payment.py)
Type | Description |
---- | ----------- |
[Language](/gopay/enums.py) | Payment language, localization of error messages |
[Token scope](/gopay/enums.py) | Authorization scope for [OAuth2](https://doc.gopay.com/en/#oauth) |
[Payment enums](/gopay/enums.py) | Enums for creating payment |
[Response enums](/gopay/enums.py) | Result 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 [`gopay.services.DefaultCache`](/gopay/services.py) 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`](/gopay/services.py) and implement its methods `get_token` and `set_token`.
Be aware that there are two [scopes](https://doc.gopay.com/#access-token) (`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:
```python
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) # 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:
```python
def logger(gopay.http.Request, gopay.http.Response) -> Any: ...
# or
Callable[[gopay.http.Response, gopay.http.Request], Any]
```
For example:
```python
from gopay.http import Request, Response
def my_logger(request: Request, response: Response) -> None:
print(vars(request))
print(vars(response))
# 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.
## Contributing
Contributions from others would be very much appreciated! Send
[pull request](https://github.com/gopaycommunity/gopay-python-api/pulls)/
[issue](https://github.com/gopaycommunity/gopay-python-api/issues). Thanks!
## License
Copyright (c) 2023 GoPay.com. MIT Licensed,
see [LICENSE](https://github.com/gopaycommunity/gopay-python-api/blob/master/LICENSE) for details.
Raw data
{
"_id": null,
"home_page": "https://github.com/gopaycommunity/gopay-python-api",
"name": "gopay",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.9",
"maintainer_email": null,
"keywords": "gopay, payments, sdk, rest, api",
"author": "GoPay",
"author_email": "integrace@gopay.cz",
"download_url": "https://files.pythonhosted.org/packages/a0/0c/9fe7b7ae83eddbddc150b80f5b18c04326f590f42266d64a387e5006c6a4/gopay-2.2.3.tar.gz",
"platform": null,
"description": "\n# GoPay's Python SDK for Payments REST API\n\n[![Build Status](https://travis-ci.org/gopaycommunity/gopay-python-api.svg?branch=master)](https://travis-ci.org/gopaycommunity/gopay-python-api)\n\n## Requirements\n\n- Python >= 3.8.1\n- dependencies:\n - [`requests`](https://github.com/kennethreitz/requests)\n - [`deprecated`](https://github.com/tantale/deprecated)\n\n## Installation\n\nThe simplest way to install SDK is to use [PIP](https://docs.python.org/3/installing/):\n\n```bash\npip install gopay\n```\n\n## Basic usage\n\n```python\nimport gopay\nfrom gopay.enums import TokenScope, Language\n\n# minimal configuration\npayments = gopay.payments({\n \"goid\": \"{{YOUR-GOID}}\",\n \"client_id\": \"{{YOUR-CLIENT-ID}}\",\n \"client_secret\": \"{{YOUR-CLIENT-SECRET}}\",\n \"gateway_url\": 'https://gw.sandbox.gopay.com/api'\n})\n\n# full configuration\npayments = gopay.payments({\n \"goid\": \"{{YOUR-GOID}}\",\n \"client_id\": \"{{YOUR-CLIENT-ID}}\",\n \"client_secret\": \"{{YOUR-CLIENT-SECRET}}\",\n \"gateway_url\": 'https://gw.sandbox.gopay.com/api'\n \"scope\": TokenScope.ALL,\n \"language\": Language.CZECH\n})\n\n# Sandbox URL: https://gw.sandbox.gopay.com/api\n# Production URL: https://gate.gopay.cz/api\n```\n\n### Configuration\n\n#### Required fields\n\nRequired field | Data type | Documentation |\n-------------- | --------- | ----------- |\n`goid` | string | GoID assigned by GoPay (production or sandbox) |\n`client_id` | string | Client ID assigned by GoPay (production or sandbox) |\n`client_secret` | string | Client Secret assigned by GoPay (production or sandbox) |\n`gateway_url` | string | URL of the environment - production or sandbox (see [Docs](https://doc.gopay.com)) |\n\n#### Optional fields\n\nOptional field | Data type | Default value | Documentation |\n-------------- | --------- | ------------- | ------------- |\n`scope` | string | [`gopay.enums.TokenScope.ALL`](gopay/enums.py) | <https://doc.gopay.com/#access-token> |\n`language` | string | [`gopay.enums.Language.ENGLISH`](gopay/enums.py) | default language to use + [localization of errors](https://doc.gopay.com/#error)\n\n### Available methods\n\nAPI | SDK method |\n--- | ---------- |\n[Create a payment](https://doc.gopay.com#payment-creation) | `payments.create_payment(payment: dict)` |\n[Get status of a payment](https://doc.gopay.com#payment-inquiry) | `payments.get_status(payment_id: str \\| int)` |\n[Refund a payment](https://doc.gopay.com#payment-refund) | `payments.refund_payment(payment_id: int \\| str, amount: int)` |\n[Create a recurring payment](https://doc.gopay.com#creating-a-recurrence) | `payments.create_recurrence(payment_id: int \\| str, payment: dict)` |\n[Cancel a recurring payment](https://doc.gopay.com#void-a-recurring-payment) | `payments.void_recurrence(payment_id: int \\| str)` |\n[Capture a preauthorized payment](https://doc.gopay.com#capturing-a-preauthorized-payment) | `payments.capture_authorization(payment_id: int \\| str)` |\n[Capture a preauthorized payment partially](https://doc.gopay.com#partially-capturing-a-preauthorized-payment) | `payments.capture_authorization_partial(payment_id: int \\| str, payment: dict)` |\n[Void a preauthorized payment](https://doc.gopay.com#voiding-a-preauthorized-payment) | `payments.void_authorization(payment_id: int \\| str)` |\n[Get payment card details](https://doc.gopay.com#payment-card-inquiry) | `payments.get_card_details(card_id: int \\| str)` |\n[Delete a saved card](https://doc.gopay.com#payment-card-deletion) | `payments.delete_card(card_id: int \\| str)` |\n[Get allowed payment methods for a currency](https://doc.gopay.com#available-payment-methods-for-a-currency) | `payments.get_payment_instruments(goid: int \\| str, currency: gopay.enums.Currency)` |\n[Get all allowed payment methods](https://doc.gopay.com#all-available-payment-methods) | `payments.get_payment_instruments_all(goid: int \\| str)` |\n[Generate an account statement](https://doc.gopay.com#account-statement) | `payments.get_account_statement(statement_request: dict)`\n\n### SDK response? Has my call succeed?\n\nSDK returns wrapped API response. Every method returns\n[`gopay.http.Response` object](gopay/http.py). Structure of the `json`\nshould be same as in [documentation](https://doc.gopay.com).\nSDK throws no exception. Please create an issue if you catch one.\n\n```python\nresponse = payments.create_payment(...)\nif response.success:\n print(f\"Hooray, API returned {response}\")\n return response.json[\"gw_url\"] # url for initiation of gateway\nelse:\n # errors format: https://doc.gopay.com#HTTP-result-codes\n print(f\"Oops, API returned {response.status_code}: {response}\")\n```\n\nProperty/Method | Description |\n------ | ---------- |\n`response.success` | Checks if API call was successful |\n`response.json` | decoded response, returned objects are converted into a dictionary if possiblem |\n`response.status_code` | HTTP status code |\n`response.raw_body` | raw bytes of the reponse content\n\n### Are required fields and allowed values validated?\n\n**Not yet.** API [validates fields](https://doc.gopay.com/#error) pretty extensively\nso there is no need to duplicate validation in SDK. That's why SDK just calls API which\nbehavior is well documented in [doc.gopay.com](https://doc.gopay.com).\nIn the future, we might use Pydantic for parsing and validation.\n\n*****\n\n## Advanced usage\n\n### Initiation of the payment gateway\n\n```python\n# create payment and pass url to template (e.g. Flask, Django)\nresponse = payments.create_payment(...)\nif response.has_succeed():\n context = {\n 'gateway_url': response.json['gw_url'],\n 'embedjs_url': payments.get_embedjs_url\n }\n # render template\n```\n\n#### [Inline gateway](https://doc.gopay.com#inline)\n\n```jinja\n<form action=\"{{ gateway_url }}\" method=\"post\" id=\"gopay-payment-button\">\n <button name=\"pay\" type=\"submit\">Pay</button>\n <script type=\"text/javascript\" src=\"{{ embedjs_url }}\"></script>\n</form>\n```\n\n#### [Redirect gateway](https://doc.gopay.com#redirect)\n\n```jinja\n<form action=\"{{ gateway_url }}\" method=\"post\">\n <button name=\"pay\" type=\"submit\">Pay</button>\n</form>\n```\n\n#### [Asynchronous initialization using JavaScript](https://doc.gopay.com#inline)\n\n### [Enums](https://doc.gopay.com#enums)\n\nInstead of hardcoding bank codes string you can use predefined enums.\nCheck using enums in [create-payment example](/examples/create_payment.py)\n\nType | Description |\n---- | ----------- |\n[Language](/gopay/enums.py) | Payment language, localization of error messages |\n[Token scope](/gopay/enums.py) | Authorization scope for [OAuth2](https://doc.gopay.com/en/#oauth) |\n[Payment enums](/gopay/enums.py) | Enums for creating payment |\n[Response enums](/gopay/enums.py) | Result of creating payment, executing payment operations |\n\n### Cache access token\n\nAccess token expires after 30 minutes it's expensive to use new token for every request.\nBy default, tokens are stored in memory [`gopay.services.DefaultCache`](/gopay/services.py) so they are reused as long as the object exists.\nBut you can implement your cache and store tokens in Memcache, Redis, files, ... It's up to you.\n\nYour cache should inherit from [`gopay.services.AbstractCache`](/gopay/services.py) and implement its methods `get_token` and `set_token`.\nBe aware that there are two [scopes](https://doc.gopay.com/#access-token) (`TokenScope`) and\nSDK 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.\nBelow you can see example implementation of caching tokens in memory:\n\n```python\nfrom gopay.services import AbstractCache\nfrom gopay.http import AccessToken\n\nclass MyCache(AbstractCache):\n def __init__(self):\n self.tokens: dict[str, AccessToken] = {}\n\n def get_token(self, key: str) -> AccessToken | None:\n return self.tokens.get(key) # return None if token doesn't exist\n\n def set_token(self, key: str, token: AccessToken) -> None:\n self.tokens[key] = token\n\n# register cache in optional service configuration\npayments = gopay.payments(\n {...}, # your config\n {\"cache\": MyCache()}\n)\n```\n\n### Log HTTP communication\n\nYou can log every request and response from communication with API. Check available loggers below.\nOr you can implement your own logger, just implement function that matches the following signature:\n\n```python\ndef logger(gopay.http.Request, gopay.http.Response) -> Any: ...\n# or\nCallable[[gopay.http.Response, gopay.http.Request], Any]\n```\n\nFor example:\n\n```python\nfrom gopay.http import Request, Response\n\ndef my_logger(request: Request, response: Response) -> None:\n print(vars(request))\n print(vars(response))\n\n# register logger in optional service configuration\npayments = gopay.payments(\n {...}, # your config\n {\"logger\": my_logger}\n)\n```\n\nThe default logger uses `logging.debug` to log the responses and requests.\n\n## Contributing\n\nContributions from others would be very much appreciated! Send\n[pull request](https://github.com/gopaycommunity/gopay-python-api/pulls)/\n[issue](https://github.com/gopaycommunity/gopay-python-api/issues). Thanks!\n\n## License\n\nCopyright (c) 2023 GoPay.com. MIT Licensed,\nsee [LICENSE](https://github.com/gopaycommunity/gopay-python-api/blob/master/LICENSE) for details.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "GoPay's Python SDK for Payments REST API",
"version": "2.2.3",
"project_urls": {
"Documentation": "https://doc.gopay.com",
"Homepage": "https://github.com/gopaycommunity/gopay-python-api",
"Repository": "https://github.com/gopaycommunity/gopay-python-api"
},
"split_keywords": [
"gopay",
" payments",
" sdk",
" rest",
" api"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "723a383e3f5f06b112e34c72484e9e4dc6b369f6752b77a579c3f6e698149d70",
"md5": "71fb3b98da37af25f67c6c24065a054c",
"sha256": "a9a5246b8d811641fd70a0f03162a23351ac85d46d35e00e9a2240dea32e650e"
},
"downloads": -1,
"filename": "gopay-2.2.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "71fb3b98da37af25f67c6c24065a054c",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9",
"size": 13350,
"upload_time": "2024-10-04T08:29:23",
"upload_time_iso_8601": "2024-10-04T08:29:23.042166Z",
"url": "https://files.pythonhosted.org/packages/72/3a/383e3f5f06b112e34c72484e9e4dc6b369f6752b77a579c3f6e698149d70/gopay-2.2.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "a00c9fe7b7ae83eddbddc150b80f5b18c04326f590f42266d64a387e5006c6a4",
"md5": "3b4d3a2149f4c46553378cad69236f07",
"sha256": "cd7b49c295e91ee9fbb30a262bff648ba933d8f027b64927d0fad9fe4ab86c26"
},
"downloads": -1,
"filename": "gopay-2.2.3.tar.gz",
"has_sig": false,
"md5_digest": "3b4d3a2149f4c46553378cad69236f07",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9",
"size": 14205,
"upload_time": "2024-10-04T08:29:25",
"upload_time_iso_8601": "2024-10-04T08:29:25.185697Z",
"url": "https://files.pythonhosted.org/packages/a0/0c/9fe7b7ae83eddbddc150b80f5b18c04326f590f42266d64a387e5006c6a4/gopay-2.2.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-04 08:29:25",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "gopaycommunity",
"github_project": "gopay-python-api",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "gopay"
}