import jwt
import datetime as dt

key_id = 'JZC9L76TDT'
alg = 'ES256'
typ = 'JWT'
issue_id = '69a6de83-02f2-47e3-e053-5b8c7c11a4d1'
aud = 'appstoreconnect-v1'
bid = 'stax.SlashPoker.nosebleed'

# Define issue timestamp.
issued_at_timestamp = int(dt.datetime.now().timestamp())
# Define expiration timestamp. May not exceed 20 minutes from issue timestamp.
expiration_timestamp = issued_at_timestamp + 59*60

# Define JWT headers.
headers = dict()
headers['alg'] = alg
headers['kid'] = key_id
headers['typ'] = typ

# Define JWT payload.
payload = dict()
payload['iss'] = issue_id
payload['iat'] = issued_at_timestamp
payload['exp'] = expiration_timestamp
payload['aud'] = aud
payload['bid'] = bid

# Path to signed private key.
KEY_FILE = 'AuthKey_JZC9L76TDT.p8'

with open(KEY_FILE,'r') as key_file:
     key = ''.join(key_file.readlines())

client_secret = jwt.encode(
payload=payload,
headers=headers,
algorithm=alg,
key=key
)

with open('jwt_signed.txt', 'w') as output:
     output.write(client_secret)

# curl -X POST -v -H 'Authorization: Bearer eyJhbGciOiJFUzI1NiIsImtpZCI6IkpaQzlMNzZURFQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiI2OWE2ZGU4My0wMmYyLTQ3ZTMtZTA1My01YjhjN2MxMWE0ZDEiLCJpYXQiOjE3MDU0MDkxNjEsImV4cCI6MTcwNTQxMjcwMSwiYXVkIjoiYXBwc3RvcmVjb25uZWN0LXYxIiwiYmlkIjoic3RheC5TbGFzaFBva2VyLm5vc2VibGVlZCJ9.BYF6iaxsFE1bDO4U3K7PB-hkhkWcbZdIvfAlq8HZyPTyUPddEufTExPH8oKnaxoZrC-wfYJTL-eNwz-1z9IJ2A' https://api.storekit-sandbox.itunes.apple.com/inApps/v1/notifications/test  
# Usage, after run this code by python3
# get token from `client_secret.txt` and replace to [signed token]
# Remember expired time maximum is 20 minutes
#
# curl -v -H 'Authorization: Bearer [signed token]' "https://api.storekit.itunes.apple.com/inApps/v1/notifications/test"
# curl -v -H 'Authorization: Bearer [signed token]' "https://api.storekit-sandbox.itunes.apple.com/inApps/v1/notifications/test"
#
# More detail https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests
