Report API: Python Example
This simple Python script retrieves the settlement data using the Report API.
To use the script:
- Update
python_config.py
with your API credentials. - Run the script:
python python-example.py
.
The settlement data will be saved in a file with a name like 2025-03-26.csv
.
info
This is provided as an example. The code works, but this is not "production quality", and we can not help with changes, improvements - or any coding help at all. See the Quick start for more details, and the API guide and API spec for all the details.
Source code: python_config.py
# Set this to:
# True: If using the MIAMI API (for accounting partners)
# False: If using merchant API keys (for merchants)
USE_MIAMI_API = True
# For all types of API users:
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
# For merchants using their own API keys: Add these in addition to the above:
SUBSCRIPTION_KEY = 'YOUR_OCP_APIM_SUBSCRIPTION_KEY'
MERCHANT_SERIAL_NUMBER = 'YOUR_MERCHANT_SERIAL_NUMBER'
Source code: python-example.py
import requests
import csv
import datetime
import base64
from python_config import CLIENT_ID, CLIENT_SECRET, SUBSCRIPTION_KEY, MERCHANT_SERIAL_NUMBER, USE_MIAMI_API
BASE_URL = 'https://api.vipps.no/settlement/v1'
TOKEN_URL_MIAMI = 'https://api.vipps.no/miami/v1/token'
TOKEN_URL_MERCHANT = 'https://api.vipps.no/accesstoken/get'
COMMON_HEADERS = {
'Vipps-System-Name': 'Report-API-Python-Example',
'Vipps-System-Version': '1.0.0',
'Vipps-System-Plugin-Name': 'Report-API-Python-Example',
'Vipps-System-Plugin-Version': '1.0.0'
}
# Get access token
def get_access_token():
if USE_MIAMI_API:
credentials = f'{CLIENT_ID}:{CLIENT_SECRET}'.encode('utf-8')
encoded_credentials = base64.b64encode(credentials).decode('utf-8')
headers = {
'Authorization': f'Basic {encoded_credentials}',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
**COMMON_HEADERS
}
data = {'grant_type': 'client_credentials'}
response = requests.post(TOKEN_URL_MIAMI, headers=headers, data=data)
else:
headers = {
'Content-Type': 'application/json',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
'Merchant-Serial-Number': MERCHANT_SERIAL_NUMBER,
**COMMON_HEADERS
}
response = requests.post(TOKEN_URL_MERCHANT, headers=headers, json={})
response.raise_for_status()
return response.json()['access_token']
# Fetch all ledgers
def get_ledgers(access_token):
url = f"{BASE_URL}/ledgers"
headers = {
'Authorization': f'Bearer {access_token}',
'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
**COMMON_HEADERS
}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
# Fetch daily settlements for a specific ledger and date
def get_daily_settlements(access_token, ledger_id, topic, date):
url = f"{BASE_URL}/ledgers/{ledger_id}/{topic}/dates/{date}"
headers = {
'Authorization': f'Bearer {access_token}',
'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY,
**COMMON_HEADERS
}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
# Save to CSV
def save_to_csv(data, filename):
with open(filename, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['PSP Reference', 'Time', 'Ledger Date', 'Entry Type', 'Reference', 'Currency', 'Amount', 'Balance Before', 'Balance After', 'Recipient Handle', 'Message', 'Name', 'Masked Phone'])
for item in data.get('items', []):
writer.writerow([
item.get('pspReference'),
item.get('time'),
item.get('ledgerDate'),
item.get('entryType'),
item.get('reference'),
item.get('currency'),
item.get('amount'),
item.get('balanceBefore'),
item.get('balanceAfter'),
item.get('recipientHandle'),
item.get('message'),
item.get('name'),
item.get('maskedPhoneNo')
])
if __name__ == "__main__":
try:
# Fetch token
token = get_access_token()
today = datetime.date.today().isoformat()
csv_filename = f"{today}.csv" # CSV file named by the date only
# Get ledgers and fetch settlements
ledgers = get_ledgers(token)
all_items = []
for ledger in ledgers.get('ledgers', []):
ledger_id = ledger.get('id')
settlements = get_daily_settlements(token, ledger_id, 'settlements', today)
all_items.extend(settlements.get('items', [])) # Fetch the items
# Save to CSV
save_to_csv({'items': all_items}, csv_filename)
print(f"Daily settlements saved to {csv_filename}")
except Exception as e:
print(f"Error: {e}")