starkinfra 0.24.0
SDK to facilitate Python integrations with Stark Infra
License: MIT License
Keywords: stark infra, starkinfra, sdk, open banking, openbanking, banking, open, stark

# Stark Infra Python SDK - Beta

Welcome to the Stark Infra Python SDK! This tool is made for Python 
developers who want to easily integrate with our API.
This SDK version is compatible with the Stark Infra API v2.

# Introduction

## Index

- [Introduction](#introduction)
    - [Supported Python versions](#supported-python-versions)
    - [API documentation](#stark-infra-api-documentation)
    - [Versioning](#versioning)
- [Setup](#setup)
    - [Install our SDK](#1-install-our-sdk)
    - [Create your Private and Public Keys](#2-create-your-private-and-public-keys)
    - [Register your user credentials](#3-register-your-user-credentials)
    - [Setting up the user](#4-setting-up-the-user)
    - [Setting up the error language](#5-setting-up-the-error-language)
- [Resource listing and manual pagination](#resource-listing-and-manual-pagination)
- [Testing in Sandbox](#testing-in-sandbox) 
- [Usage](#usage)
    - [Issuing](#issuing)
        - [Products](#query-issuingproducts): View available sub-issuer card products (a.k.a. card number ranges or BINs)
        - [Holders](#create-issuingholders): Manage card holders
        - [Cards](#create-issuingcards): Create virtual and/or physical cards
        - [Design](#query-issuingdesigns): View your current card or package designs
        - [EmbossingKit](#query-issuingembossingkits): View your current embossing kits
        - [Stock](#query-issuingstocks): View your current stock of a certain IssuingDesign linked to an Embosser on the workspace
        - [Restock](#create-issuingrestocks): Create restock orders of a specific IssuingStock object
        - [EmbossingRequest](#create-issuingembossingrequests): Create embossing requests
        - [TokenRequest](#create-an-issuingtokenrequest): Generate the payload to create the token
        - [Token](#process-token-authorizations): Authorize and manage your tokens
        - [TokenActivation](#process-token-activations): Get notified on how to inform the activation code to the holder 
        - [TokenDesign](#get-an-issuingtokendesign): View your current token card arts
        - [Purchases](#process-purchase-authorizations): Authorize and view your past purchases
        - [Invoices](#create-issuinginvoices): Add money to your issuing balance
        - [Withdrawals](#create-issuingwithdrawals): Send money back to your Workspace from your issuing balance
        - [Balance](#get-your-issuingbalance): View your issuing balance
        - [Transactions](#query-issuingtransactions): View the transactions that have affected your issuing balance
        - [Enums](#issuing-enums): Query enums related to the issuing purchases, such as merchant categories, countries and card purchase methods
        - [Billing Invoices](#issuing-billinginvoice): View your current billing invoices
        - [Billing Transactions](#issuing-billingtransaction): View your current billing transactions
    - [Pix](#pix)
        - [PixRequests](#create-pixrequests): Create Pix transactions
        - [PixReversals](#create-pixreversals): Reverse Pix transactions
        - [PixBalance](#get-your-pixbalance): View your account balance
        - [PixStatement](#create-a-pixstatement): Request your account statement
        - [PixKey](#create-a-pixkey): Create a Pix Key
        - [PixClaim](#create-a-pixclaim): Claim a Pix Key
        - [PixDirector](#create-a-pixdirector): Create a Pix Director
        - [PixInfraction](#create-pixinfractions): Create Pix Infraction reports
        - [PixFraud](#create-a-pixfraud): Create a Pix Fraud 
        - [PixUser](#get-a-pixuser): Get fraud statistics of a user
        - [PixChargeback](#create-pixchargebacks): Create Pix Chargeback requests
        - [PixDomain](#query-pixdomains): View registered SPI participants certificates
        - [StaticBrcode](#create-staticbrcodes): Create static Pix BR codes
        - [DynamicBrcode](#create-dynamicbrcodes): Create dynamic Pix BR codes
        - [BrcodePreview](#create-brcodepreviews): Read data from BR Codes before paying them
        - [PixDispute](#create-pixdisputes): Create Pix Disputes
    - [Lending](#lending)
        - [CreditNote](#create-creditnotes): Create credit notes
        - [CreditPreview](#create-creditpreviews): Create credit previews
        - [CreditHolmes](#create-creditholmes): Create credit holmes debt verification
    - [Identity](#identity)
        - [IndividualIdentity](#create-individualidentities): Create individual identities
        - [IndividualDocument](#create-individualdocuments): Create individual documents
    - [Webhook](#webhook):
        - [Webhook](#create-a-webhook-subscription): Configure your webhook endpoints and subscriptions
        - [WebhookEvents](#process-webhook-events): Manage Webhook events
        - [WebhookEventAttempts](#query-failed-webhook-event-delivery-attempts-information): Query failed webhook event deliveries
    - [Request](#request): Send a custom request to Stark Bank. This can be used to access features that haven't been mapped yet.
- [Handling errors](#handling-errors)
- [Help and Feedback](#help-and-feedback)

## Supported Python Versions

This library supports the following Python versions:

* Python 2.7
* Python 3.4+

## Stark Infra API documentation

Feel free to take a look at our [API docs](https://www.starkinfra.com/docs/api).

## Versioning

This project adheres to the following versioning pattern:

Given a version number MAJOR.MINOR.PATCH, increment:

- MAJOR version when the **API** version is incremented. This may include backwards incompatible changes;
- MINOR version when **breaking changes** are introduced OR **new functionalities** are added in a backwards compatible manner;
- PATCH version when backwards compatible bug **fixes** are implemented.

# Setup

## 1. Install our SDK

1.1 To install the package with pip, run:

```sh
pip install starkinfra
```

1.2 To install from source, clone the repo and run:

```sh
python setup.py install
```

## 2. Create your Private and Public Keys

We use ECDSA. That means you need to generate a secp256k1 private
key to sign your requests to our API, and register your public key
with us, so we can validate those requests.

You can use one of the following methods:

2.1. Check out the options in our [tutorial](https://starkbank.com/faq/how-to-create-ecdsa-keys). 

2.2. Use our SDK:

```python
import starkinfra

privateKey, publicKey = starkinfra.key.create()

# or, to also save .pem files in a specific path
privateKey, publicKey = starkinfra.key.create("file/keys/")
```

**NOTE**: When you are creating new credentials, it is recommended that you create the
keys inside the infrastructure that will use it, in order to avoid risky internet
transmissions of your **private-key**. Then you can export the **public-key** alone to the
computer where it will be used in the new Project creation.

## 3. Register your user credentials

You can interact directly with our API using two types of users: Projects and Organizations.

- **Projects** are workspace-specific users, that is, they are bound to the workspaces they are created in.
One workspace can have multiple Projects.
- **Organizations** are general users that control your entire organization.
They can control all your Workspaces and even create new ones. The Organization is bound to your company's tax ID only.
Since this user is unique in your entire organization, only one credential can be linked to it.

3.1. To create a Project in Sandbox:

3.1.1. Log into [StarkInfra Sandbox](https://web.sandbox.starkinfra.com)

3.1.2. Go to Menu > Integrations

3.1.3. Click on the "New Project" button

3.1.4. Create a Project: Give it a name and upload the public key you created in section 2

3.1.5. After creating the Project, get its Project ID

3.1.6. Use the Project ID and private key to create the object below:

```python
import starkinfra

# Get your private key from an environment variable or an encrypted database.
# This is only an example of a private key content. You should use your own key.
private_key_content = """
-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIMCwW74H6egQkTiz87WDvLNm7fK/cA+ctA2vg/bbHx3woAcGBSuBBAAK
oUQDQgAE0iaeEHEgr3oTbCfh8U2L+r7zoaeOX964xaAnND5jATGpD/tHec6Oe9U1
IF16ZoTVt1FzZ8WkYQ3XomRD4HS13A==
-----END EC PRIVATE KEY-----
"""

project = starkinfra.Project(
    environment="sandbox",
    id="5656565656565656",
    private_key=private_key_content
)
```

3.2. To create Organization credentials in Sandbox:

3.2.1. Log into [Starkinfra Sandbox](https://web.sandbox.starkinfra.com)

3.2.2. Go to Menu > Integrations

3.2.3. Click on the "Organization public key" button

3.2.4. Upload the public key you created in section 2 (only a legal representative of the organization can upload the public key)

3.2.5. Click on your profile picture and then on the "Organization" menu to get the Organization ID

3.2.6. Use the Organization ID and private key to create the object below:

```python
import starkinfra

# Get your private key from an environment variable or an encrypted database.
# This is only an example of a private key content. You should use your own key.
private_key_content = """
-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIMCwW74H6egQkTiz87WDvLNm7fK/cA+ctA2vg/bbHx3woAcGBSuBBAAK
oUQDQgAE0iaeEHEgr3oTbCfh8U2L+r7zoaeOX964xaAnND5jATGpD/tHec6Oe9U1
IF16ZoTVt1FzZ8WkYQ3XomRD4HS13A==
-----END EC PRIVATE KEY-----
"""

organization = starkinfra.Organization(
    environment="sandbox",
    id="5656565656565656",
    private_key=private_key_content,
    workspace_id=None,  # You only need to set the workspace_id when you are operating a specific workspace_id
)

```

NOTE 1: Never hard-code your private key. Get it from an environment variable or an encrypted database.

NOTE 2: We support `'sandbox'` and `'production'` as environments.

NOTE 3: The credentials you registered in `sandbox` do not exist in `production` and vice versa.


## 4. Setting up the user

There are three kinds of users that can access our API: **Organization**, **Project**, and **Member**.

- `Project` and `Organization` are designed for integrations and are the ones meant for our SDKs.
- `Member` is the one you use when you log into our webpage with your e-mail.

There are two ways to inform the user to the SDK:

4.1 Passing the user as an argument in all functions:

```python
import starkinfra

balance = starkinfra.pixbalance.get(user=project)  # or organization
```

4.2 Set it as a default user in the SDK:

```python
import starkinfra

starkinfra.user = project  # or organization

balance = starkinfra.pixbalance.get()
```

Just select the way of passing the user that is more convenient to you.
On all following examples, we will assume a default user has been set.

## 5. Setting up the error language

The error language can also be set in the same way as the default user:

```python
import starkinfra

starkinfra.language = "en-US"
```

Language options are "en-US" for English and "pt-BR" for Brazilian Portuguese. English is the default.

# Resource listing and manual pagination

Almost all SDK resources provide a `query` and a `page` function.

- The `query` function provides a straightforward way to efficiently iterate through all results that match the filters you inform,
seamlessly retrieving the next batch of elements from the API only when you reach the end of the current batch.
If you are not worried about data volume or processing time, this is the way to go.

```python
import starkinfra

for request in starkinfra.pixrequest.query(limit=200):
    print(request)
```

- The `page` function gives you full control over the API pagination. With each function call, you receive up to
100 results and the cursor to retrieve the next batch of elements. This allows you to stop your queries and
pick up from where you left off whenever it is convenient. When there are no more elements to be retrieved, the returned cursor will be `None`.

```python
import starkinfra

cursor = None
while True:
    requests, cursor = starkinfra.pixrequest.page(limit=50, cursor=cursor)
    for request in requests:
        print(request)
    if cursor is None:
        break
```

To simplify the following SDK examples, we will only use the `query` function, but feel free to use `page` instead.

# Testing in Sandbox

Your initial balance is zero. For many operations in Stark Infra, you'll need funds
in your account, which can be added to your balance by creating a starkbank.Invoice. 

In the Sandbox environment, most of the created starkbank.Invoices will be automatically paid,
so there's nothing else you need to do to add funds to your account. Just create
a few starkbank.Invoice and wait around a bit.

In Production, you (or one of your clients) will need to actually pay this Pix Request
for the value to be credited to your account.


# Usage

Here are a few examples on how to use the SDK. If you have any doubts, use the built-in
`help()` function to get more info on the desired functionality
(for example: `help(starkinfra.issuinginvoice.create)`)

## Issuing

### Query IssuingProducts

To take a look at the sub-issuer card products available to you, just run the following:

```python
import starkinfra

products = starkinfra.issuingproduct.query()

for product in products:
    print(product)
```

This will tell which card products and card number prefixes you have at your disposal.

### Create IssuingHolders

You can create card holders to which your cards will be bound.
They support spending rules that will apply to all underlying cards.

```python
import starkinfra

holders = starkinfra.issuingholder.create([
    starkinfra.IssuingHolder(
        name="Iron Bank S.A.",
        external_id="1234",
        tax_id="012.345.678-90",
        tags=[
            "Traveler Employee"
        ],
        rules=[
            {
                "name": "General USD",
                "interval": "day",
                "amount": 100000,
                "currencyCode": "USD",
                "categories": [
                    {
                        "type": "services"
                    },
                    {
                        "code": "fastFoodRestaurants"
                    }
                ],
                "countries": [
                    {
                        "code": "USA"
                    }
                ],
                "methods": [
                    {
                        "code": "token"
                    }
                ]
            }
        ]
    )
])

for holder in holders:
    print(holder)
```

**Note**: Instead of using IssuingHolder objects, you can also pass each element in dictionary format

### Query IssuingHolders

You can query multiple holders according to filters.

```python
import starkinfra

holders = starkinfra.issuingholder.query()

for holder in holders:
    print(holder)
```

### Cancel an IssuingHolder

To cancel a single Issuing Holder by its id, run:

```python
import starkinfra

holder = starkinfra.issuingholder.cancel("5155165527080960")

print(holder)
```

### Get an IssuingHolder

To get a specific Issuing Holder by its id, run:

```python
import starkinfra

holder = starkinfra.issuingholder.get("5155165527080960")

print(holder)
```

### Query IssuingHolder logs

You can query IssuingHolder logs to better understand IssuingHolder life cycles.

```python
import starkinfra

logs = starkinfra.issuingholder.log.query(limit=50)

for log in logs:
    print(log.id)
```

### Get an IssuingHolder log

You can also get a specific log by its id.

```python
import starkinfra

log = starkinfra.issuingholder.log.get("5155165527080960")

print(log)
```

### Create IssuingCards

You can issue cards with specific spending rules.

```python
import starkinfra

cards = starkinfra.issuingcard.create([
    starkinfra.IssuingCard(
        holder_name="Developers",
        holder_tax_id="012.345.678-90",
        holder_external_id="1234",
        rules=[starkinfra.IssuingRule(
            name="general",
            interval="week",
            amount=50000,
            currency_code="USD",
            categories=[
                starkinfra.MerchantCategory(type="services"),  # Covers all service-related MCCs
                starkinfra.MerchantCategory(code="fastFoodRestaurants")  # Covers a specific MCC
            ],
            countries=[
                starkinfra.MerchantCountry(code="BRA")
            ],
            methods=[
                starkinfra.CardMethod(code="token")
            ]
        )]
    )
])

for card in cards:
    print(card)
```

### Query IssuingCards

You can get a list of created cards given some filters.

```python
import starkinfra
from datetime import date

cards = starkinfra.issuingcard.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)

for card in cards:
    print(card)
```

### Get an IssuingCard

After its creation, information on a card may be retrieved by its id.

```python
import starkinfra

card = starkinfra.issuingcard.get("5155165527080960")

print(card)
```

### Update an IssuingCard

You can update a specific card by its id.

```python
import starkinfra

card = starkinfra.issuingcard.update("5155165527080960", status="blocked")

print(card)
```

### Cancel an IssuingCard

You can also cancel a card by its id.

```python
import starkinfra

card = starkinfra.issuingcard.cancel("5155165527080960")

print(card)
```

### Query IssuingCard logs

Logs are pretty important to understand the life cycle of a card.

```python
import starkinfra

logs = starkinfra.issuingcard.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingCard log

You can get a single log by its id.

```python
import starkinfra

log = starkinfra.issuingcard.log.get("5155165527080960")

print(log)
```

### Query IssuingDesigns

You can get a list of available designs given some filters.

```python
import starkinfra

designs = starkinfra.issuingdesign.query(
    limit=1
)

for design in designs:
    print(design)
```

### Get an IssuingDesign

Information on a design may be retrieved by its id.

```python
import starkinfra

design = starkinfra.issuingdesign.get("5747368922185728")

print(design)
```

### Query IssuingEmbossingKits

You can get a list of existing embossing kits given some filters.

```python
import starkinfra
from datetime import date

kits = starkinfra.issuingembossingkit.query(
    after=date(2022, 11, 1),
    before=date(2022, 12, 1)
)

for kit in kits:
    print(kit)
```

### Get an IssuingEmbossingKit

After its creation, information on an embossing kit may be retrieved by its id.

```python
import starkinfra

kit = starkinfra.issuingembossingkit.get("5664445921492992")

print(kit)
```

### Query IssuingStocks

You can get a list of available stocks given some filters.

```python
import starkinfra
from datetime import date

stocks = starkinfra.issuingstock.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)

for stock in stocks:
    print(stock)
```

### Get an IssuingStock

Information on a stock may be retrieved by its id.

```python
import starkinfra

stock = starkinfra.issuingstock.get("5792731695677440")

print(stock)
```

### Query IssuingStock logs

Logs are pretty important to understand the life cycle of a stock.

```python
import starkinfra

logs = starkinfra.issuingstock.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingStock log

You can get a single log by its id.

```python
import starkinfra

log = starkinfra.issuingstock.log.get("5809977331548160")

print(log)
```

### Create IssuingRestocks

You can order restocks for a specific IssuingStock.

```python
import starkinfra

restocks = starkinfra.issuingrestock.create([
    starkinfra.IssuingRestock(
        count=100,
        stock_id="5136459887542272"
    )
])

for restock in restocks:
    print(restock)
```

### Query IssuingRestocks

You can get a list of created restocks given some filters.

```python
import starkinfra
from datetime import date

restocks = starkinfra.issuingrestock.query(
    after=date(2022, 11, 1),
    before=date(2022, 12, 1)
)

for restock in restocks:
    print(restock)
```

### Get an IssuingRestock

After its creation, information on a restock may be retrieved by its id.

```python
import starkinfra

restock = starkinfra.issuingrestock.get("5664445921492992")

print(restock)
```

### Query IssuingRestock logs

Logs are pretty important to understand the life cycle of a restock.

```python
import starkinfra

logs = starkinfra.issuingrestock.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingRestock log

You can get a single log by its id.

```python
import starkinfra

log = starkinfra.issuingrestock.log.get("6310318875607040")

print(log)
```

### Create IssuingEmbossingRequests

You can create a request to emboss a physical card.

```python
import starkinfra

embossing_requests = starkinfra.issuingembossingrequest.create([
    starkinfra.IssuingEmbossingRequest(
        kit_id="5648359658356736", 
        card_id="5714424132272128", 
        display_name_1="Antonio Stark", 
        shipping_city="Sao Paulo",
        shipping_country_code="BRA",
        shipping_district="Bela Vista",
        shipping_service="loggi",
        shipping_state_code="SP",
        shipping_street_line_1="Av. Paulista, 200",
        shipping_street_line_2="10 andar",
        shipping_tracking_number="My_custom_tracking_number",
        shipping_zip_code="12345-678",
        embosser_id="5746980898734080"
    )
])

for embossing_request in embossing_requests:
    print(embossing_request)
```

### Query IssuingEmbossingRequests

You can get a list of created embossing requests given some filters.

```python
import starkinfra
from datetime import date

embossing_requests = starkinfra.issuingembossingrequest.query(
    after=date(2022, 11, 1),
    before=date(2022, 12, 1)
)

for embossing_request in embossing_requests:
    print(embossing_request)
```

### Get an IssuingEmbossingRequest

After its creation, information on an embossing request may be retrieved by its id.

```python
import starkinfra

embossing_request = starkinfra.issuingembossingrequest.get("5191752558313472")

print(embossing_request)
```

### Query IssuingEmbossingRequest logs

Logs are pretty important to understand the life cycle of an embossing request.

```python
import starkinfra

logs = starkinfra.issuingembossingrequest.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingEmbossingRequest log

You can get a single log by its id.

```python
import starkinfra

log = starkinfra.issuingembossingrequest.log.get("6724771005857792")

print(log)
```
### Create an IssuingTokenRequest

You can create a request that provides the required data you must send to the wallet app.

```python
import starkinfra

request = starkinfra.issuingtokenrequest.create(
    starkinfra.IssuingTokenRequest(
        card_id="5189831499972623",
        wallet_id="google",
        method_code="app"
    )
)

print(request)
```

### Process Token authorizations

It's easy to process token authorizations delivered to your endpoint.
Remember to pass the signature header so the SDK can make sure it's StarkInfra that sent you the event.
If you do not approve or decline the authorization within 2 seconds, the authorization will be denied.

```python
import starkinfra

request = listen()  # this is the method you made to get the events posted to your tokenAuthorizationUrl endpoint

authorization = starkinfra.issuingtoken.parse(
    content=request.data.decode("utf-8"),
    signature=request.headers["Digital-Signature"],
)

sendResponse(
    starkinfra.issuingtoken.response_authorization( # this optional method just helps you build the response JSON
        status="approved",
        activation_methods=[
            {
                "type": "app",
                "value": "com.subissuer.android"
            },
            {
                "type": "text",
                "value": "** *****-5678"
            }
        ],
        design_id="4584031664472031",
        tags=["token", "user/1234"],
    )
)

# or

sendResponse(
    starkinfra.issuingtoken.response_authorization( # this optional method just helps you build the response JSON
        status="denied",
        reason="other",
    )
)
```

### Process Token activations

It's easy to process token activation notifications delivered to your endpoint.
Remember to pass the signature header so the SDK can make sure it's Stark Infra that sent you the event.

```python
import starkinfra

request = listen()  # this is the method you made to get the events posted to your tokenActivationUrl endpoint

authorization = starkinfra.issuingtokenactivation.parse(
    content=request.data.decode("utf-8"),
    signature=request.headers["Digital-Signature"],
)
```

After that, you may generate the activation code and send it to the cardholder.
The cardholder enters the received code in the wallet app. We'll receive and send it to
tokenAuthorizationUrl for your validation. Completing the provisioning process. 

```python
import starkinfra

request = listen()  # this is the method you made to get the events posted to your tokenAuthorizationUrl endpoint

activation = starkinfra.issuingtoken.parse(
    content=request.data.decode("utf-8"),
    signature=request.headers["Digital-Signature"],
)

sendResponse(
    starkinfra.issuingtoken.response_activation( # this optional method just helps you build the response JSON
        status="approved",
        tags=["token", "user/1234"]
    )
)

# or

sendResponse(
    starkinfra.issuingtoken.response_activation( # this optional method just helps you build the response JSON
        status="denied",
        reason="other",
        tags=["token", "user/1234"]
    )
)
```

### Get an IssuingToken

You can get a single token by its id.

```python
import starkinfra

token = starkinfra.issuingtoken.get(id="5749080709922816")

print(token)
```

### Query IssuingTokens

You can get a list of created tokens given some filters.

```python
import starkinfra

tokens = starkinfra.issuingtoken.query(
    limit=5,
    after=date.today() - timedelta(days=100),
    before=date.today(),
    status="active",
    card_ids=["5656565656565656", "4545454545454545"],
    external_ids=["DSHRMC00002626944b0e3b539d4d459281bdba90c2588791", "DSHRMC00002626941c531164a0b14c66ad9602ee716f1e85"]
)

for token in tokens:
    print(token)
```
 
### Update an IssuingToken

You can update a specific token by its id.

```python
import starkinfra

token = starkinfra.issuingtoken.update(id="5155165527080960", status="blocked")

print(token)
```

### Cancel an IssuingToken

You can also cancel a token by its id.

```python
import starkinfra

token = starkinfra.issuingtoken.cancel(id="5155165527080960")

print(token)
```

### Get an IssuingTokenDesign

You can get a single design by its id.

```python
import starkinfra

design = starkinfra.issuingtokendesign.get(id="5749080709922816")

print(design)
```
### Query IssuingTokenDesigns 

You can get a list of available designs given some filters.

```python
import starkinfra

designs = starkinfra.issuingtokendesign.query(limit=5)

for design in designs:
    print(design)
```

## Get an IssuingTokenDesign PDF

A design PDF can be retrieved by its id. 

```python
import starkinfra

pdf = starkinfra.issuingtokendesign.pdf(id="5155165527080960")

with open("design.pdf", "wb") as file:
    file.write(pdf)
```


### Process Purchase authorizations

It's easy to process purchase authorizations delivered to your endpoint.
Remember to pass the signature header so the SDK can make sure it's StarkInfra that sent you the event.
If you do not approve or decline the authorization within 2 seconds, the authorization will be denied.

```python
import starkinfra

request = listen()  # this is the method you made to get the events posted to your tokenActivationUrl endpoint

authorization = starkinfra.issuingpurchase.parse(
    content=request.data.decode("utf-8"),
    signature=request.headers["Digital-Signature"],
)

sendResponse(  # you should also implement this method
    starkinfra.issuingpurchase.response(  # this optional method just helps you build the response JSON
        status="approved",
        amount=authorization.amount,
        tags=["my-purchase-id/123"],
    )
)

# or 

sendResponse(
    starkinfra.issuingpurchase.response(
        status="denied",
        reason="other",
        tags=["other-id/456"],
    )
)
```

### Query IssuingPurchases

You can get a list of created purchases given some filters.

```python
import starkinfra
from datetime import date

purchases = starkinfra.issuingpurchase.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)

for purchase in purchases:
    print(purchase)
```

### Get an IssuingPurchase

After its creation, information on a purchase may be retrieved by its id. 

```python
import starkinfra

purchase = starkinfra.issuingpurchase.get("5155165527080960")

print(purchase)
```

### Update an IssuingPurchase

You can update a specific IssuingPurchase by its id.

```python
import starkinfra

purchase = starkinfra.issuingpurchase.update("5155165527080960", description="Dinner", tags=["customer-x", "reimbursement"])

print(purchase)
```

### Query IssuingPurchase logs

Logs are pretty important to understand the life cycle of a purchase.

```python
import starkinfra

logs = starkinfra.issuingpurchase.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingPurchase log

You can get a single log by its id.

```python
import starkinfra

log = starkinfra.issuingpurchase.log.get("5155165527080960")

print(log)
```

### Create IssuingInvoices

You can create Pix invoices to transfer money from accounts you have in any bank to your Issuing balance,
allowing you to run your issuing operation.

```python
import starkinfra

invoice = starkinfra.issuinginvoice.create(
    invoice=starkinfra.IssuingInvoice(
        amount=1000
    )
)

print(invoice)
```

**Note**: Instead of using IssuingInvoice objects, you can also pass each element in dictionary format

### Get an IssuingInvoice

After its creation, information on an invoice may be retrieved by its id. 
Its status indicates whether it's been paid.

```python
import starkinfra

invoice = starkinfra.issuinginvoice.get("5155165527080960")

print(invoice)
```

### Query IssuingInvoices

You can get a list of created invoices given some filters.

```python
import starkinfra
from datetime import date

invoices = starkinfra.issuinginvoice.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)

for invoice in invoices:
    print(invoice)
```

### Query IssuingInvoice logs

Logs are pretty important to understand the life cycle of an invoice.

```python
import starkinfra

logs = starkinfra.issuinginvoice.log.query(limit=150)

for log in logs:
    print(log)
```

### Get an IssuingInvoice log

You can also get a specific log by its id.

```python
import starkinfra

log = starkinfra.issuinginvoice.log.get("5155165527080960")

print(log)
```

### Create IssuingWithdrawals

You can create withdrawals to send cash back from your Issuing balance to your Banking balance
by using the IssuingWithdrawal resource.

```python
import starkinfra

withdrawal = starkinfra.issuingwithdrawal.create(
    withdrawal=starkinfra.IssuingWithdrawal(
        amount=10000,
        external_id="123",
        description="Sending back"
    )
)

print(withdrawal)
```

**Note**: Instead of using IssuingWithdrawal objects, you can also pass each element in dictionary format

### Get an IssuingWithdrawal

After its creation, information on a withdrawal may be retrieved by its id.

```python
import starkinfra

invoice = starkinfra.issuingwithdrawal.get("5155165527080960")

print(invoice)
```

### Query IssuingWithdrawals

You can get a list of created withdrawals given some filters.

```python
import starkinfra
from datetime import date

withdrawals = starkinfra.issuingwithdrawal.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)

for withdrawal in withdrawals:
    print(withdrawal)
```

### Get your IssuingBalance

To know how much money you have available to run authorizations, run:

```python
import starkinfra

balance = starkinfra.issuingbalance.get()

print(balance)
```

### Query IssuingTransactions

To understand your balance changes (issuing statement), you can query
transactions. Note that our system creates transactions for you when
you make purchases, withdrawals, receive issuing invoice payments, for example.

```python
import starkinfra
from datetime import date

transactions = starkinfra.issuingtransaction.query(
    after=date(2020, 1, 1),
    before=date(2020, 3, 1)
)
for transaction in transactions:
    print(transaction)
```

### Get an IssuingTransaction

You can get a specific transaction by its id:

```python
import starkinfra

transaction = starkinfra.issuingtransaction.get("5155165527080960")

print(transaction)
```

### Issuing Enums

#### Query MerchantCategories

You can query any merchant categories using this resource.
You may also use MerchantCategories to define specific category filters in IssuingRules.
Either codes (which represents specific MCCs) or types (code groups) will be accepted as filters.

```python
import starkinfra

categories = starkinfra.merchantcategory.query(
    search="food",
)

for category in categories:
    print(category)
```

#### Query MerchantCountries

You can query any merchant countries using this resource.
You may also use MerchantCountries to define specific country filters in IssuingRules.

```python
import starkinfra

countries = starkinfra.merchantcountry.query(
    search="brazil",
)

for country in countries:
    print(country)
```

#### Query CardMethods

You can query available card methods using this resource.
You may also use CardMethods to define specific purchase method filters in IssuingRules.

```python
import starkinfra

methods = starkinfra.cardmethod.query(
    search="token",
)

for method in methods:
    print(method)
```

### Query IssuingBillingInvoices

You can query multiples available Billing Invoices using this resource.

```python
import starkinfra
from datetime import date

billing_invoices = starkinfra.issuingbillinginvoice.query(
    after=date(2023, 1, 1),
    before=date(2024, 3, 1),
    limit=10
)

for billing_invoice in billing_invoices:
    print(billing_invoice)
```

### Get an IssuingBillingInvoice

```python
import starkinfra

billing_invoice = starkinfra.issuingbillinginvoice.get("9302937674764487")

print(billing_invoice)
```

### Query IssuingBillingTransactions

You can query multiples available Billing Transaction invoices using this resource.

```python
import starkinfra
from datetime import date

billing_transactions = starkinfra.issuingbillingtransaction.query(
    after=date(2023, 1, 1),
    before=date(2024, 3, 1),
    limit=10
)

for billing_transaction in billing_transactions:
    print(billing_transaction)
```

## Pix

### Create PixRequests

You can create a Pix request to transfer money from one of your users to anyone else:

```python
import starkinfra

requests = starkinfra.pixrequest.create([
    starkinfra.PixRequest(
        amount=100,  # (R$ 1.00)
        external_id="141234121",  # so we can block anything you send twice by mistake
        sender_branch_code="0000",
        sender_account_number="00000-0",
        sender_account_type="checking",
        sender_name="Tyrion Lannister",
        sender_tax_id="012.345.678-90",
        receiver_bank_code="00000001",
        receiver_branch_code="0001",
        receiver_account_number="00000-1",
        receiver_account_type="checking",
        receiver_name="Jamie Lannister",
        receiver_tax_id="45.987.245/0001-92",
        end_to_end_id=starkinfra.endtoendid.create("20018183"),  # Pass your bank code to create an end to end ID
        description="For saving my life",
    ),
    starkinfra.PixRequest(
        amount=200,  # (R$ 2.00)
        external_id="2135613462",  # so we can block anything you send twice by mistake
        sender_account_number="00000-0",
        sender_branch_code="0000",
        sender_account_type="checking",
        sender_name="Arya Stark",
        sender_tax_id="012.345.678-90",
        receiver_bank_code="00000001",
        receiver_account_number="00000-1",
        receiver_branch_code="0001",
        receiver_account_type="checking",
        receiver_name="John Snow",
        receiver_tax_id="012.345.678-90",
        end_to_end_id=starkinfra.endtoendid.create("20018183"),  # Pass your bank code to create an end to end ID
        tags=["Needle", "sword"],
    )
])

for request in requests:
    print(request)
```

**Note**: Instead of using PixRequest objects, you can also pass each element in dictionary format

### Query PixRequests

You can query multiple Pix requests according to filters.

```python
import starkinfra
from datetime import date

requests = starkinfra.pixrequest.query(
    limit=10,
    after=date(2020, 1, 1),
    before=date(2020, 4, 1),
    status="success",
    tags=["iron", "suit"],
    end_to_end_ids=["E79457883202101262140HHX553UPqeq"],
)

for request in requests:
    print(request)
```

### Get a PixRequest

After its creation, information on a Pix request may be retrieved by its id. Its status indicates whether it has been paid.

```python
import starkinfra

request = starkinfra.pixrequest.get("5155165527080960")

print(request)
```

### Process inbound PixRequest authorizations

It's easy to process authorization requests that arrived at your endpoint.
Remember to pass the signature header so the SDK can make sure it's StarkInfra that sent you the event.
If you do not approve or decline the authorization within 1 second, the authorization will be denied.

```python
import starkinfra

request = listen()  # this is your handler to listen for authorization requests

pix_request = starkinfra.pixrequest.parse(
    content=request.data.decode("utf-8"),
    signature=request.headers["Digital-Signature"],
)

print(pix_request)

sendResponse(  # you should also implement this method
    starkinfra.pixrequest.response(  # this optional method just helps you build the response JSON
        status="approved",
    )
)

# or 

sendResponse(
    starkinfra.pixrequest.response(
        status="denied",
        reason="orderRejected",
    )
)
```
  
### Query PixRequest logs

You can query Pix request logs to better understand Pix request life cycles. 

```python
import starkinfra
from datetime import date

logs = starkinfra.pixrequest.log.query(
    limit=50, 
    after=date(2022, 1, 1),
    before=date(2022, 1, 20),
)

for log in logs:
    print(log)
```

### Get a PixRequest log

You can also get a specific log by its id.

```python
import starkinfra

log = starkinfra.pixrequest.log.get("5155165527080960")

print(log)
```

### Create PixReversals

You can reverse a PixRequest either partially or totally using a PixReversal.

```python
import starkinfra

reversal = starkinfra.pixreversal.create([
    starkinfra.PixReversal(
        amount=100,
        end_to_end_id="E00000000202201060100rzsJzG9PzMg",
        external_id="17238435823958934",
        reason="bankError",
    )
])

print(reversal)
```

### Query PixReversals 

You can query multiple Pix reversals according to filters. 

```python
import starkinfra
from datetime import date

reversals = starkinfra.pixreversal.query(
    limit=10,
    after=date(2020, 1, 1),
    before=date(2020, 4, 1),
    status="success",
    tags=["iron", "suit"],
    return_ids=["D20018183202202030109X3OoBHG74wo"],
)

for reversal in reversals:
    print(reversal)
```

### Get a PixReversal

After its creation, information on a Pix reversal may be retrieved by its id.
Its status indicates whether it has been successfully processed.

```python
import starkinfra