Add prototype PayPal subscriber report.

This commit is contained in:
Ben Sturmfels 2021-11-19 13:17:46 +11:00
commit d298456efe
Signed by: bsturmfels
GPG key ID: 023C05E2C9C068F0

72
paypal_report.py Normal file
View file

@ -0,0 +1,72 @@
"""Download subscriber info from PayPal.
Run it like this:
$ export PAYPAL_CLIENT_ID=XXX
$ export PAYPAL_CLIENT_SECRET=YYY
$ python3 paypal_report.py 2021-11-01T00:00:00-0700 2021-11-30T23:59:59-0700 > out.csv
"""
import argparse
import csv
import sys
import os
import requests
def get_access_token(client_id, client_secret):
url = 'https://api-m.paypal.com/v1/oauth2/token?grant_type=client_credentials'
response = requests.post(
url,
auth=(client_id, client_secret),
headers={
'Accept': 'application/json',
'Accept-Language': 'en_US',
},
)
data = response.json()
return data['access_token']
def get_transactions(access_token, start_date, end_date, page=1):
print(f'Fetching transactions page {page}.', file=sys.stderr)
url = f'https://api-m.paypal.com/v1/reporting/transactions?start_date={start_date}&end_date={end_date}&fields=all&page_size=500&page={page}'
response = requests.get(
url,
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {access_token}',
},
)
data = response.json()
if page < data['total_pages']:
return data['transaction_details'] + get_transactions(access_token, start_date, end_date, page + 1)
else:
return data['transaction_details']
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Download PayPal subscriber info.')
parser.add_argument('start_date', help='start date inclusive (eg. 2021-11-01T00:00:00-0700)')
parser.add_argument('end_date', help='end date inclusive (eg. 2021-11-30T23:59:59-0700)')
args = parser.parse_args()
try:
client_id = os.environ['PAYPAL_CLIENT_ID']
client_secret = os.environ['PAYPAL_CLIENT_SECRET']
except KeyError:
sys.exit('Please set PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET environment variables.')
access_token = get_access_token(client_id, client_secret)
transactions = get_transactions(access_token, args.start_date, args.end_date)
writer = csv.writer(sys.stdout)
for t in transactions:
transaction_info = t['transaction_info']
if 'paypal_reference_id' in transaction_info:
writer.writerow(
(
transaction_info['paypal_reference_id'],
transaction_info['transaction_subject'],
),
)
else:
print(f'Skipping transaction {transaction_info["transaction_id"]} with no PayPal Reference ID.', file=sys.stderr)