binance-sdk-pay 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 - 2025-07-17
4
+
5
+ - Initial release
README.md ADDED
@@ -0,0 +1,177 @@
1
+ # Binance Python Pay SDK
2
+
3
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/binance/binance-connector-python/ci-pay.yml)](https://github.com/binance/binance-connector-python/actions)
4
+ [![Open Issues](https://img.shields.io/github/issues/binance/binance-connector-python)](https://github.com/binance/binance-connector-python/issues)
5
+ [![Code Style: Black](https://img.shields.io/badge/code_style-black-black)](https://black.readthedocs.io/en/stable/)
6
+ [![PyPI version](https://img.shields.io/pypi/v/binance-sdk-pay)](https://pypi.python.org/pypi/binance-sdk-pay)
7
+ [![PyPI Downloads](https://img.shields.io/pypi/dm/binance-sdk-pay.svg)](https://pypi.org/project/binance-sdk-pay/)
8
+ [![Python version](https://img.shields.io/pypi/pyversions/binance-connector)](https://www.python.org/downloads/)
9
+ [![Known Vulnerabilities](https://img.shields.io/badge/security-scanned-brightgreen)](https://github.com/binance/binance-connector-python/security)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
11
+
12
+ This is a client library for the Binance Pay SDK API, enabling developers to interact programmatically with Binance's Pay trading platform. The library provides tools to query transaction history through the REST API:
13
+
14
+ - [REST API](./src/binance_sdk_pay/rest_api/rest_api.py)
15
+
16
+ ## Table of Contents
17
+
18
+ - [Supported Features](#supported-features)
19
+ - [Installation](#installation)
20
+ - [Documentation](#documentation)
21
+ - [REST APIs](#rest-apis)
22
+ - [Testing](#testing)
23
+ - [Migration Guide](#migration-guide)
24
+ - [Contributing](#contributing)
25
+ - [Licence](#licence)
26
+
27
+ ## Supported Features
28
+
29
+ - REST API Endpoints:
30
+ - `/sapi/v1/pay/*`
31
+ - Inclusion of test cases and examples for quick onboarding.
32
+
33
+ ## Installation
34
+
35
+ To use this library, ensure your environment is running Python version **3.9** or later.
36
+
37
+ ```bash
38
+ pip install binance-sdk-pay
39
+ ```
40
+
41
+ ## Documentation
42
+
43
+ For detailed information, refer to the [Binance API Documentation](https://developers.binance.com/docs/pay/Introduction).
44
+
45
+ ### REST APIs
46
+
47
+ All REST API endpoints are available through the [`rest_api`](./src/binance_sdk_pay/rest_api/rest_api.py) module. The REST API enables you to fetch market data, manage trades, and access account information. Note that some endpoints require authentication using your Binance API credentials.
48
+
49
+ ```python
50
+ from binance_common.configuration import ConfigurationRestAPI
51
+ from binance_common.constants import PAY_REST_API_PROD_URL
52
+ from binance_sdk_pay.pay import Pay
53
+ from binance_sdk_pay.rest_api.models import GetPayTradeHistoryResponse
54
+
55
+ logging.basicConfig(level=logging.INFO)
56
+ configuration = ConfigurationRestAPI(api_key="your-api-key", api_secret="your-api-secret", base_path=PAY_REST_API_PROD_URL)
57
+
58
+ client = Pay(config_rest_api=configuration)
59
+
60
+ try:
61
+ response = client.rest_api.get_pay_trade_history(startTimestamp=1637186702000, limit=50)
62
+
63
+ data: GetPayTradeHistoryResponse = response.data()
64
+ logging.info(f"get_pay_trade_history() response: {data}")
65
+ except Exception as e:
66
+ logging.error(f"get_pay_trade_history() error: {e}")
67
+ ```
68
+
69
+ More examples can be found in the [`examples/rest_api`](./examples/rest_api/) folder.
70
+
71
+ #### Configuration Options
72
+
73
+ The REST API supports the following advanced configuration options:
74
+
75
+ - `timeout`: Timeout for requests in milliseconds (default: 1000 ms).
76
+ - `proxy`: Proxy configuration:
77
+ - `host`: Proxy server hostname.
78
+ - `port`: Proxy server port.
79
+ - `protocol`: Proxy protocol (http or https).
80
+ - `auth`: Proxy authentication credentials:
81
+ - `username`: Proxy username.
82
+ - `password`: Proxy password.
83
+ - `keep_alive`: Enable HTTP keep-alive (default: true).
84
+ - `compression`: Enable response compression (default: true).
85
+ - `retries`: Number of retry attempts for failed requests (default: 3).
86
+ - `backoff`: Delay in milliseconds between retries (default: 1000 ms).
87
+ - `https_agent`: Custom HTTPS agent for advanced TLS configuration.
88
+ - `private_key`: RSA or ED25519 private key for authentication.
89
+ - `private_key_passphrase`: Passphrase for the private key, if encrypted.
90
+
91
+ ##### Timeout
92
+
93
+ You can configure a timeout for requests in milliseconds. If the request exceeds the specified timeout, it will be aborted. See the [Timeout example](./docs/rest_api/timeout.md) for detailed usage.
94
+
95
+ ##### Proxy
96
+
97
+ The REST API supports HTTP/HTTPS proxy configurations. See the [Proxy example](./docs/rest_api/proxy.md) for detailed usage.
98
+
99
+ ##### Keep-Alive
100
+
101
+ Enable HTTP keep-alive for persistent connections. See the [Keep-Alive example](./docs/rest_api/keepAlive.md) for detailed usage.
102
+
103
+ ##### Compression
104
+
105
+ Enable or disable response compression. See the [Compression example](./docs/rest_api/compression.md) for detailed usage.
106
+
107
+ ##### Retries
108
+
109
+ Configure the number of retry attempts and delay in milliseconds between retries for failed requests. See the [Retries example](./docs/rest_api/retries.md) for detailed usage.
110
+
111
+ ##### HTTPS Agent
112
+
113
+ Customize the HTTPS agent for advanced TLS configurations. See the [HTTPS Agent example](./docs/rest_api/httpsAgent.md) for detailed usage.
114
+
115
+ ##### Key Pair Based Authentication
116
+
117
+ The REST API supports key pair-based authentication for secure communication. You can use `RSA` or `ED25519` keys for signing requests. See the [Key Pair Based Authentication example](./docs/rest_api/key-pair-authentication.md) for detailed usage.
118
+
119
+ ##### Certificate Pinning
120
+
121
+ To enhance security, you can use certificate pinning with the `https_agent` option in the configuration. This ensures the client only communicates with servers using specific certificates. See the [Certificate Pinning example](./docs/rest_api/certificate-pinning.md) for detailed usage.
122
+
123
+ #### Error Handling
124
+
125
+ The REST API provides detailed error types to help you handle issues effectively:
126
+
127
+ - `ClientError`: Represents an error that occurred in the SDK client.
128
+ - `RequiredError`: Thrown when a required parameter is missing or undefined.
129
+ - `UnauthorizedError`: Indicates missing or invalid authentication credentials.
130
+ - `ForbiddenError`: Access to the requested resource is forbidden.
131
+ - `TooManyRequestsError`: Rate limit exceeded.
132
+ - `RateLimitBanError`: IP address banned for exceeding rate limits.
133
+ - `ServerError`: Internal server error, optionally includes a status code.
134
+ - `NetworkError`: Issues with network connectivity.
135
+ - `NotFoundError`: Resource not found.
136
+ - `BadRequestError`: Invalid request or one that cannot be served.
137
+
138
+ See the [Error Handling example](./docs/rest_api/error-handling.md) for detailed usage.
139
+
140
+ If `base_path` is not provided, it defaults to `https://api.binance.com`.
141
+
142
+ ## Testing
143
+
144
+ To run the tests, ensure you have [Poetry](https://python-poetry.org/) installed, then execute the following commands:
145
+
146
+ ```bash
147
+ poetry install
148
+ poetry run pytest ./tests
149
+ ```
150
+
151
+ The tests cover:
152
+ * REST API endpoints
153
+ * Error handling
154
+ * Edge cases
155
+
156
+ ## Migration Guide
157
+
158
+ If you are upgrading to the new modularized structure, refer to the [Migration Guide](./docs/migration_guide_pay_sdk.md) for detailed steps.
159
+
160
+ ## Contributing
161
+
162
+ Contributions are welcome!
163
+
164
+ Since this repository contains auto-generated code, we encourage you to start by opening a GitHub issue to discuss your ideas or suggest improvements. This helps ensure that changes align with the project's goals and auto-generation processes.
165
+
166
+ To contribute:
167
+
168
+ 1. Open a GitHub issue describing your suggestion or the bug you've identified.
169
+ 2. If it's determined that changes are necessary, the maintainers will merge the changes into the main branch.
170
+
171
+ Please ensure that all tests pass if you're making a direct contribution. Submit a pull request only after discussing and confirming the change.
172
+
173
+ Thank you for your contributions!
174
+
175
+ ## Licence
176
+
177
+ This project is licensed under the MIT License. See the [LICENCE](./LICENCE) file for details.
@@ -0,0 +1,31 @@
1
+ from binance_sdk_pay.pay import Pay
2
+ from binance_common.errors import (
3
+ ClientError,
4
+ RequiredError,
5
+ UnauthorizedError,
6
+ ForbiddenError,
7
+ TooManyRequestsError,
8
+ RateLimitBanError,
9
+ ServerError,
10
+ NetworkError,
11
+ NotFoundError,
12
+ BadRequestError,
13
+ )
14
+ from binance_common.constants import (
15
+ PAY_REST_API_PROD_URL,
16
+ )
17
+
18
+ __all__ = [
19
+ "Pay",
20
+ "PAY_REST_API_PROD_URL",
21
+ "ClientError",
22
+ "RequiredError",
23
+ "UnauthorizedError",
24
+ "ForbiddenError",
25
+ "TooManyRequestsError",
26
+ "RateLimitBanError",
27
+ "ServerError",
28
+ "NetworkError",
29
+ "NotFoundError",
30
+ "BadRequestError",
31
+ ]
@@ -0,0 +1 @@
1
+ NAME = "binance-sdk-pay"
binance_sdk_pay/pay.py ADDED
@@ -0,0 +1,34 @@
1
+ import platform
2
+ from importlib.metadata import version
3
+
4
+ from binance_common.configuration import ConfigurationRestAPI
5
+ from binance_common.constants import PAY_REST_API_PROD_URL
6
+ from . import metadata
7
+ from .rest_api import PayRestAPI
8
+
9
+ LIB_NAME = metadata.NAME
10
+ LIB_VERSION = version(LIB_NAME)
11
+
12
+
13
+ class Pay:
14
+ """Pay API that exposes REST APIs in a single interface."""
15
+
16
+ def __init__(self, config_rest_api: ConfigurationRestAPI = None) -> None:
17
+ self._rest_api = None
18
+ self._rest_api_config = (
19
+ ConfigurationRestAPI() if config_rest_api is None else config_rest_api
20
+ )
21
+
22
+ @property
23
+ def rest_api(self) -> PayRestAPI:
24
+ if self._rest_api is None and self._rest_api_config:
25
+ self._rest_api_config.base_headers["User-Agent"] = (
26
+ f"{LIB_NAME}/{LIB_VERSION} (Python/{platform.python_version()}; {platform.system()}; {platform.machine()})"
27
+ )
28
+ self._rest_api_config.base_path = (
29
+ PAY_REST_API_PROD_URL
30
+ if self._rest_api_config.base_path is None
31
+ else self._rest_api_config.base_path
32
+ )
33
+ self._rest_api = PayRestAPI(self._rest_api_config)
34
+ return self._rest_api
@@ -0,0 +1,13 @@
1
+ """
2
+ Binance Pay REST API
3
+
4
+ OpenAPI Specification for the Binance Pay REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .rest_api import PayRestAPI
12
+
13
+ __all__ = ["PayRestAPI"]
@@ -0,0 +1,11 @@
1
+ """
2
+ Binance Pay REST API
3
+
4
+ OpenAPI Specification for the Binance Pay REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .pay_api import PayApi as PayApi
@@ -0,0 +1,122 @@
1
+ """
2
+ Binance Pay REST API
3
+
4
+ OpenAPI Specification for the Binance Pay REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from typing import Optional
12
+ from requests import Session
13
+ from binance_common.configuration import ConfigurationRestAPI
14
+ from binance_common.models import ApiResponse
15
+ from binance_common.signature import Signers
16
+ from binance_common.utils import send_request
17
+
18
+ from ..models import GetPayTradeHistoryResponse
19
+
20
+
21
+ class PayApi:
22
+ """API Client for PayApi endpoints."""
23
+
24
+ def __init__(
25
+ self,
26
+ configuration: ConfigurationRestAPI = None,
27
+ session: Session = None,
28
+ signer: Signers = None,
29
+ ) -> None:
30
+ self._configuration = configuration
31
+ self._session = session
32
+ self._signer = signer
33
+
34
+ def get_pay_trade_history(
35
+ self,
36
+ start_time: Optional[int] = None,
37
+ end_time: Optional[int] = None,
38
+ limit: Optional[int] = None,
39
+ recv_window: Optional[int] = None,
40
+ ) -> ApiResponse[GetPayTradeHistoryResponse]:
41
+ """
42
+ Get Pay Trade History
43
+ GET /sapi/v1/pay/transactions
44
+ https://developers.binance.com/docs/pay/rest-api/Get-Pay-Trade-History
45
+
46
+ Get Pay Trade History
47
+
48
+ * If startTime and endTime are not sent, the recent 90 days' data will be returned.
49
+ * The max interval between startTime and endTime is 90 days.
50
+ * Support for querying orders within the last 18 months.
51
+ * For payerInfo and receiverInfo,there are different return values in different orderTypes.
52
+ * Sender's perspective when orderType is C2C
53
+ * payerInfo : binanceId
54
+ * receiverInfo : name, binanceId/accountId/email/countryCode/phoneNumber/mobileCode (based on user input)
55
+ * Receiver's perspective when orderType is C2C
56
+ * payerInfo : name, accountId
57
+ * receiverInfo : binanceId
58
+ * Sender's perspective when orderType is CRYPTO_BOX
59
+ * payerInfo : binanceId
60
+ * receiverInfo : name(the value is always "Crypto Box")
61
+ * Receiver's perspective when orderType is CRYPTO_BOX
62
+ * payerInfo : name, accountId
63
+ * receiverInfo : binanceId
64
+ * Sender's perspective when orderType is PAY
65
+ * payerInfo : binanceId
66
+ * receiverInfo : name
67
+ * Receiver's perspective when orderType is PAY
68
+ * payerInfo : name, accountId
69
+ * receiverInfo : binanceId, name
70
+ * Sender's perspective when orderType is PAY_REFUND
71
+ * payerInfo : binanceId, name
72
+ * receiverInfo : name, accountId
73
+ * Receiver's perspective when orderType is PAY_REFUND
74
+ * payerInfo : name
75
+ * receiverInfo : binanceId
76
+ * Sender's perspective when orderType is PAYOUT
77
+ * payerInfo : binanceId, name
78
+ * receiverInfo : name, accountId
79
+ * Receiver's perspective when orderType is PAYOUT
80
+ * payerInfo : name
81
+ * receiverInfo : binanceId
82
+ * Receiver's perspective when orderType is CRYPTO_BOX_RF
83
+ * payerInfo : name(the value is always "Crypto Box")
84
+ * receiverInfo : binanceId
85
+ * Sender's perspective when orderType is REMITTANCE
86
+ * payerInfo : binanceId
87
+ * receiverInfo : name, institutionName, cardNumber, digitalWalletId
88
+
89
+ Weight: 3000
90
+
91
+ Args:
92
+ start_time (Optional[int]):
93
+ end_time (Optional[int]):
94
+ limit (Optional[int]): default 100, max 100
95
+ recv_window (Optional[int]):
96
+
97
+ Returns:
98
+ ApiResponse[GetPayTradeHistoryResponse]
99
+
100
+ Raises:
101
+ RequiredError: If a required parameter is missing.
102
+
103
+ """
104
+
105
+ payload = {
106
+ "start_time": start_time,
107
+ "end_time": end_time,
108
+ "limit": limit,
109
+ "recv_window": recv_window,
110
+ }
111
+
112
+ return send_request(
113
+ self._session,
114
+ self._configuration,
115
+ method="GET",
116
+ path="/sapi/v1/pay/transactions",
117
+ payload=payload,
118
+ time_unit=self._configuration.time_unit,
119
+ response_model=GetPayTradeHistoryResponse,
120
+ is_signed=True,
121
+ signer=self._signer,
122
+ )
@@ -0,0 +1,31 @@
1
+ """
2
+ Binance Pay REST API
3
+
4
+ OpenAPI Specification for the Binance Pay REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
10
+
11
+ from .get_pay_trade_history_response import (
12
+ GetPayTradeHistoryResponse as GetPayTradeHistoryResponse,
13
+ )
14
+ from .get_pay_trade_history_response_data_inner import (
15
+ GetPayTradeHistoryResponseDataInner as GetPayTradeHistoryResponseDataInner,
16
+ )
17
+ from .get_pay_trade_history_response_data_inner_funds_detail_inner import (
18
+ GetPayTradeHistoryResponseDataInnerFundsDetailInner as GetPayTradeHistoryResponseDataInnerFundsDetailInner,
19
+ )
20
+ from .get_pay_trade_history_response_data_inner_funds_detail_inner_wallet_asset_cost_inner import (
21
+ GetPayTradeHistoryResponseDataInnerFundsDetailInnerWalletAssetCostInner as GetPayTradeHistoryResponseDataInnerFundsDetailInnerWalletAssetCostInner,
22
+ )
23
+ from .get_pay_trade_history_response_data_inner_payer_info import (
24
+ GetPayTradeHistoryResponseDataInnerPayerInfo as GetPayTradeHistoryResponseDataInnerPayerInfo,
25
+ )
26
+ from .get_pay_trade_history_response_data_inner_receiver_info import (
27
+ GetPayTradeHistoryResponseDataInnerReceiverInfo as GetPayTradeHistoryResponseDataInnerReceiverInfo,
28
+ )
29
+ from .get_pay_trade_history_response_data_inner_receiver_info_extend import (
30
+ GetPayTradeHistoryResponseDataInnerReceiverInfoExtend as GetPayTradeHistoryResponseDataInnerReceiverInfoExtend,
31
+ )
@@ -0,0 +1,9 @@
1
+ """
2
+ Binance Pay REST API
3
+
4
+ OpenAPI Specification for the Binance Pay REST API
5
+ The version of the OpenAPI document: 1.0.0
6
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
7
+
8
+ Do not edit the class manually.
9
+ """
@@ -0,0 +1,129 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Binance Pay REST API
5
+
6
+ OpenAPI Specification for the Binance Pay REST API
7
+ The version of the OpenAPI document: 1.0.0
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """
12
+
13
+
14
+ from __future__ import annotations
15
+ import pprint
16
+ import re # noqa: F401
17
+ import json
18
+
19
+ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr
20
+ from typing import Any, ClassVar, Dict, List, Optional
21
+ from binance_sdk_pay.rest_api.models.get_pay_trade_history_response_data_inner import (
22
+ GetPayTradeHistoryResponseDataInner,
23
+ )
24
+ from typing import Set
25
+ from typing_extensions import Self
26
+
27
+
28
+ class GetPayTradeHistoryResponse(BaseModel):
29
+ """
30
+ GetPayTradeHistoryResponse
31
+ """ # noqa: E501
32
+
33
+ code: Optional[StrictStr] = None
34
+ message: Optional[StrictStr] = None
35
+ data: Optional[List[GetPayTradeHistoryResponseDataInner]] = None
36
+ success: Optional[StrictBool] = None
37
+ additional_properties: Dict[str, Any] = {}
38
+ __properties: ClassVar[List[str]] = ["code", "message", "data", "success"]
39
+
40
+ model_config = ConfigDict(
41
+ populate_by_name=True,
42
+ validate_assignment=True,
43
+ protected_namespaces=(),
44
+ )
45
+
46
+ def to_str(self) -> str:
47
+ """Returns the string representation of the model using alias"""
48
+ return pprint.pformat(self.model_dump(by_alias=True))
49
+
50
+ def to_json(self) -> str:
51
+ """Returns the JSON representation of the model using alias"""
52
+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
53
+ return json.dumps(self.to_dict())
54
+
55
+ @classmethod
56
+ def is_array(cls) -> bool:
57
+ return False
58
+
59
+ @classmethod
60
+ def from_json(cls, json_str: str) -> Optional[Self]:
61
+ """Create an instance of GetPayTradeHistoryResponse from a JSON string"""
62
+ return cls.from_dict(json.loads(json_str))
63
+
64
+ def to_dict(self) -> Dict[str, Any]:
65
+ """Return the dictionary representation of the model using alias.
66
+
67
+ This has the following differences from calling pydantic's
68
+ `self.model_dump(by_alias=True)`:
69
+
70
+ * `None` is only added to the output dict for nullable fields that
71
+ were set at model initialization. Other fields with value `None`
72
+ are ignored.
73
+ * Fields in `self.additional_properties` are added to the output dict.
74
+ """
75
+ excluded_fields: Set[str] = set(
76
+ [
77
+ "additional_properties",
78
+ ]
79
+ )
80
+
81
+ _dict = self.model_dump(
82
+ by_alias=True,
83
+ exclude=excluded_fields,
84
+ exclude_none=True,
85
+ )
86
+ # override the default output from pydantic by calling `to_dict()` of each item in data (list)
87
+ _items = []
88
+ if self.data:
89
+ for _item_data in self.data:
90
+ if _item_data:
91
+ _items.append(_item_data.to_dict())
92
+ _dict["data"] = _items
93
+ # puts key-value pairs in additional_properties in the top level
94
+ if self.additional_properties is not None:
95
+ for _key, _value in self.additional_properties.items():
96
+ _dict[_key] = _value
97
+
98
+ return _dict
99
+
100
+ @classmethod
101
+ def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
102
+ """Create an instance of GetPayTradeHistoryResponse from a dict"""
103
+ if obj is None:
104
+ return None
105
+
106
+ if not isinstance(obj, dict):
107
+ return cls.model_validate(obj)
108
+
109
+ _obj = cls.model_validate(
110
+ {
111
+ "code": obj.get("code"),
112
+ "message": obj.get("message"),
113
+ "data": (
114
+ [
115
+ GetPayTradeHistoryResponseDataInner.from_dict(_item)
116
+ for _item in obj["data"]
117
+ ]
118
+ if obj.get("data") is not None
119
+ else None
120
+ ),
121
+ "success": obj.get("success"),
122
+ }
123
+ )
124
+ # store additional fields in additional_properties
125
+ for _key in obj.keys():
126
+ if _key not in cls.__properties:
127
+ _obj.additional_properties[_key] = obj.get(_key)
128
+
129
+ return _obj