foreignexchangerates

WANJIK
Dabbler

foreignexchangerates

I wrote a code to get exchange rate information with python, but it doesn't work. I'm new to coding, so what's the problem?

 

 

 

 

import datetime
import hashlib
import hmac
import json
import logging
from calendar import timegm

import requests


# DEBUG = False
DEBUG = True

 

try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPSConnection.debuglevel = 0

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True


api_key = '***'
shared_secret = '***'

print("START Sample Code for API Key- Shared Secret (X-Pay-Token)")

print(datetime.datetime.now())
date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")


url = 'https://sandbox.api.visa.com/forexrates/v2/foreignexchangerates'
headers = {}
body = {}

payload = json.loads('''{}
''')

timeout = 10

query_string = "apiKey=" + api_key
resource_path = "/forexrates/v2/foreignexchangerates"
body = ""

secret = bytes(shared_secret, 'utf-8')
timestamp = str(timegm(datetime.datetime.utcnow().timetuple()))
pre_hash_string = bytes(timestamp + resource_path + query_string + body, 'utf-8')
print(pre_hash_string)
hash_string = hmac.new(secret, pre_hash_string, digestmod=hashlib.sha256).hexdigest()
x_pay_token = 'xv2:' + timestamp + ':' + hash_string
print(x_pay_token)

 

 

headers = {'x-pay-token': x_pay_token, 'Content-Type': 'application/json'}
payload = {
"initiatingPartyId": 1002,
"rateProductCode": "BANK",
"destinationCurrencyCode": "USD",
"sourceCurrencyCode": "EUR",
"quoteIdRequired": True
}
try:
# response = requests.get(url + '?' + query_string,
# headers=headers,
# timeout=timeout
# # if DEBUG: print (response.text)
# )
response = requests.post(url + '?' + query_string,
headers=headers,
json=payload,
timeout=timeout)
except Exception as e:
print(e)

if response.status_code == 200:
data = response.json()
exchange_rate = data.get("rate")
print(exchange_rate)
else:
print("API request failed.")
print(response)

2 REPLIES 2
jenn_kh
Community Moderator

Re: foreignexchangerates

Thank you for reaching out, @WANJIK. One of our agents will get back to you as soon as possible. In the meantime, if any community members know the solution, feel free to share it here!

I_Doroteo3
Visa Developer Support Specialist

Re: foreignexchangerates

Hi @WANJIK

 

Have you tried running the FX Rates sample payload that is provided on the API Reference page?

 

I also noticed you are using X-Pay Token as the authentication method- FX Rates API uses mutual SSL authentication and channel encryption; you can learn more about this using this link.

 

Thanks, 

Illana