liquichain-api-python 0.1.1
Liquichain API client for Python
License: BSD
Keywords: liquichain,blockchain,cryptocurrency,payment,service,direct debit,refunds,payments,gateway

<p align="center">
  <img src="https://docs.liquichain.io/media/python-api/logo_python_liquichain.png" width="128" height="128"/>
</p>
<h1 align="center">Liquichain API client for Python</h1>

<img src="https://docs.liquichain.io/media/python-api/editor-1.png" />

Accepting Licoin, Paypal, online payments without fixed monthly costs or any punishing registration procedures. Just use the Liquichain API to receive payments directly on your website or easily refund transactions to your customers.

[![PyPI version](https://badge.fury.io/py/liquichain-api-python.svg)](http://badge.fury.io/py/liquichain-api-python)
[![Build Status](https://travis-ci.com/liquichain/liquichain-api-python.svg?branch=master)](https://travis-ci.org/liquichain/liquichain-api-python)

## Requirements ##
To use the Liquichain API client, the following things are required:

+ Get yourself a free [Liquichain account](https://account.liquichain.io/). No sign up costs.
+ Create a new [Website profile](https://account.liquichain.io/dashboard/settings/profiles) to generate API keys and setup your webhook.
+ Now you're ready to use the Liquichain API client in test mode.
+ Follow [a few steps](https://account.liquichain.io/dashboard/?modal=onboarding) to enable payment methods in live mode, and let us handle the rest.
+ Python >= 3.6
+ Up-to-date OpenSSL (or other SSL/TLS toolkit)
+ Liquichain API client for Python has a dependency on [Requests](http://docs.python-requests.org/en/master/) and [Requests-OAuthlib](https://requests-oauthlib.readthedocs.io/en/latest/)

## Installation ##

By far the easiest way to install the Liquichain API client is to install it with [pip](https://pip.pypa.io). The command below will install the latest released version of the client.
```
$ pip install liquichain-api-python
```
You may also git checkout or [download all the files](https://github.com/liquichain/liquichain-api-python/archive/master.zip), and include the Liquichain API client manually.

Create and activate a Python >= 3.6 virtual environment (inside a git checkout or downloaded archive).

```
$ cd liquichain-api-python
$ python -m venv .venv
$ source .venv/bin/activate
```

Install the additional requirements for the examples, then install the Liquichain API client itself.
```
$ pip install flask
$ pip install -e .
```

Run the examples.
```
export LIQUICHAIN_API_KEY=test_YourApiKey
$ python examples/app.py
```

## How to receive payments ##

To successfully receive a payment, these steps should be implemented:

1. Use the Liquichain API client to create a payment with the requested amount, tocken symbol (LIC for licoin), description and optionally, a payment method. It is important to specify a unique redirect URL where the customer is supposed to return to after the payment is completed.

2. Immediately after the payment is completed, our platform will send an asynchronous request to the configured webhook to allow the payment details to be retrieved, so you know when exactly to start processing the customer's order.

3. The customer returns, and should be satisfied to see that the order was paid and is now being processed.

Find our full documentation online on [docs.liquichain.io](https://docs.liquichain.io).

## Getting started ##

Importing the Liquichain API Client
```python
from liquichain.api.client import Client
``` 
Initializing the Liquichain API client, and setting your API key

```python
liquichain_client = Client()
liquichain_client.set_api_key('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM')
``` 

Creating a new payment.

```python
payment = liquichain_client.payments.create({
    'amount': {
        'currency': 'LIC',
        'value': '0.00000001' 
    },
    'description': 'My first API payment',
    'redirectUrl': 'https://webshop.example.org/order/12345/',
    'webhookUrl': 'https://webshop.example.org/liquichain-webhook/',
})
```
_After creation, the payment id is available in the `payment.id` property. You should store this id with your order._

After storing the payment id you can send the customer to the checkout using the `payment.checkout_url`.  

For a payment create example, see [Example 1 - New Payment](https://github.com/liquichain/liquichain-api-python/blob/master/examples/01-new-payment.py).

In general, request body parameters for an API endpoint should be added to a dictionary and provided as the first argument (or `data` keyword argument). Query string parameters can be provided as keyword arguments.

## Retrieving payments ##
We can use the `payment.id` to retrieve a payment and check if the payment `isPaid`.

```python
payment = liquichain_client.payments.get(payment.id)

if payment.is_paid():
    print('Payment received.')
```

Or retrieve a collection of payments.

```python
payments = liquichain_client.payments.list()
```

For an extensive example of listing payments with the details and status, see [Example 5 - Payments History](https://github.com/liquichain/liquichain-api-python/blob/master/examples/05-payments-history.py).

## Payment webhook ##

When the status of a payment changes the `webhookUrl` we specified in the creation of the payment will be called.  
There we can use the `id` from our POST parameters to check te status and act upon that, see [Example 2 - Webhook verification](https://github.com/liquichain/liquichain-api-python/blob/master/examples/02-webhook-verification.py).


## Multicurrency (paying with tokens) ##
Payments using liquichain tokens is now supported.
A full list of available tokens can be found [in our documentation](https://docs.liquichain.io/guides/multicurrency).

```python
payment = liquichain_client.payments.create({
    'amount': {
        'currency': 'TOK', 
        'value': '10.00'
    },
    'description': 'Order #12345',
    'redirectUrl': 'https://webshop.example.org/order/12345/',
    'webhookUrl': 'https://webshop.example.org/liquichain-webhook/',
})
```
_After the customer completes the payment, the `payment.settlement_amount` will contain the amount + currency that will be settled on your account._

### Refunding payments ###

The API also supports refunding payments. Note that there is no confirmation and that all refunds are immediate and
definitive. Refunds are only supported for Licoin. Other types of payments cannot be refunded through our API at the moment.

```python
payment = liquichain_client.payments.get(payment.id)

# Refund € 2 of this payment
refund = liquichain_client.refunds.on(payment).create({
    'amount': {
        'currency': 'LCN',
        'value': '0.0000000001'
    }
})
```

For a working example, see [Example 11 - Refund payment](https://github.com/liquichain/liquichain-api-python/blob/master/examples/11-refund-payment.py).

## Oauth2 ##

At https://docs.liquichain.io/oauth/getting-started the oauth process is explained. Please read this first.

Oauth authentication process redirects back to your application. Therefore you should expose your local web server (the examples) as public urls. A webservice like [ngrok.com](https://ngrok.com/) can help you with that. Make sure to set REDIRECT_URI accordingly.

Run the oauth2 examples:

```
FLASK_APP=examples/oauth/app.py \
CLIENT_ID=your_client_id \
CLIENT_SECRET=your_client_secret \
REDIRECT_URI=https://your_domain.tld/callback \
flask run
```

The Authorize endpoint is the endpoint on the Liquichain web site where the merchant logs in, and grants authorization to your client application. E.g. when the merchant clicks on the Connect with Liquichain button, you should redirect the merchant to the Authorize endpoint.

The resource owner can then grant the authorization to your client application for the scopes you have requested.

Liquichain will then redirect the resource owner back to the `redirect_uri` you have specified. The redirect_uri will be appended with a code parameter, which will contain the auth token. At the redirect_uri, you should extract that token, and use it to request a regular oauth token.

### Initializing via oauth2 ###

You should implement the `get_token` and `set_token` methods yourself. They should retrieve and store the oauth token that is sent from Liquichain somewhere in your application (f.i. in the database).

The token data is a python dict.

These are example methods, you should use a storage method that fits your application.

```python

def get_token():
    """
    :return: token (dict) or None
    """
    if os.path.exists('token.json'):
        with open('token.json', 'r') as file:
            return json.loads(file.read())


def set_token(token):
    """
    :param token: token (dict)
    :return: None
    """
    with open('token.json', 'w') as file:
        file.write(json.dumps(token))


liquichain_client = Client()
is_authorized, authorization_url = liquichain_client.setup_oauth(
    client_id,
    client_secret,
    redirect_uri,
    scope,
    get_token(),
    set_token,
)
# When "is_authorized" is False, you need to redirect the user to the authorization_url.

# After the user confirmed she is redirected back to your redirect_uri.
# The view on this uri should call setup_oauth_authorization_response(), with authorization_response as parameter.
# This is the full callback URL (string)

liquichain.setup_oauth_authorization_response(authorization_response)

# The token will be stored via your `set_token` method for future use. Expired tokens will be refreshed by the client automatically.

# Now You can query the API:

liquichain.organizations.get('me')
```

## API documentation ##
If you wish to learn more about our API, please visit the [Liquichain Developer Portal](https://www.liquichain.io/en/developers). API Documentation is available in English.

## Want to help us make our API client even better? ##

Want to help us make our API client even better? We take [pull requests](https://github.com/liquichain/liquichain-api-python/pulls?utf8=%E2%9C%93&q=is%3Apr).

## License ##
[BSD (Berkeley Software Distribution) License](https://opensource.org/licenses/bsd-license.php).
Copyright (c) 2014-2020, [Mollie B.V.](https://www.mollie.com) whose original source code comes from

## Support ##
Contact: [liquichain.io](https://liquichain.io)