Problem with Python encrypted request.post - python-3.x

I have a problem with encrypted post requests. The encrypted algorithm is AES/ECB/PKCS5Padding and API settings are here: https://bondevalue.com/app/apiInstructions client_token is working. But I always receive 'Seems you are providing invalid input data. Provide data in valid format.'
import requests
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
client_token = b'ae3rncr14cngemft'
requestData = b'{\"data\":{\"userToken\":\"[ae3rncr14cngemft]\"},\"bondISINId\":\"[XS1401197253]\", \"fromDate\":\"[2016-12-07]\"}'
cipher1 = AES.new(client_token, AES.MODE_ECB)
requestEncrypted = str(base64.b64encode(cipher1.encrypt(pad(requestData, 16, 'pkcs7'))), 'utf-8')
url = 'https://bondevalue.com/app/bondDetailsHistoryData'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'requestData': requestEncrypted}
answer = requests.post(url=url, data=requestEncrypted, headers=headers)
response = answer.json()

Related

How do I pass an API Token into Cookie via Python Request?

I'm having issues w/ authenticating to pkgs.org api, a token was produced, by support mentioned it needs to be passed as a cookie. I've never worked with cookies before.
import requests
import json
import base64
import urllib3
import sys
import re
import os
token=('super-secret')
#s = requests.Session()
head = {'Accept':'application/json'}
r = requests.get('https://api.pkgs.org/v1/distributions', auth=(token), headers=head)
print(r)
print(r.connection)
print(r.cookies)
I tried to use the request.session method, to handle the cookie, but i honestly don't know syntax on how to ever 1 create a cookie, let alone pass the cookie.
If I read the API documentation correctly you should set acces_token cookie:
import requests
token = "super-secret"
cookies = {"access_token": token}
headers = {"Accept": "application/json"}
r = requests.get(
"https://api.pkgs.org/v1/distributions", cookies=cookies, headers=headers
)

Unable to Access API

I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?
I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved

Exception has occurred: JSONDecodeError App Store Connect Financial API using Python

I am trying to get financial data from my APP store connect account and am receiving a JSON error, see below:
import requests, time, json
from authlib.jose import jwt
KEY_ID = "KEY"
ISSUER_ID = "ID"
EXPIRATION_TIME = int(round(time.time() + (20.0 * 60.0))) # 20 minutes timestamp
PATH_TO_KEY = "C:\\Users\\justi\\Desktop\\Script Files\\App Store Connect\\private_key\\AuthKey_KEY.p8"
with open(PATH_TO_KEY, 'r') as f:
PRIVATE_KEY = f.read()
header = {
"alg": "ES256",
"kid": KEY_ID,
"typ": "JWT"
}
payload = {
"iss": ISSUER_ID,
"exp": EXPIRATION_TIME,
"aud": "appstoreconnect-v1"
}
# Create the JWT
token = jwt.encode(header, payload, PRIVATE_KEY)
# URL Query Params
report_type = "filter[reportType]=FINANCE_DETAIL"
region_code = "filter[regionCode]=Z1"
report_date = "filter[reportDate]=2021-03"
vendor_number = "filter[vendorNumber]=VEND_###"
# API Request
JWT = 'Bearer ' + token.decode()
URL = 'https://api.appstoreconnect.apple.com/v1/financeReports?'+ report_type +'&' +region_code+ '&' + report_date + '&' +vendor_number
HEAD = {'Authorization': JWT}
r = requests.get(URL, params={'limit': 200}, headers=HEAD)
# Write the response in a pretty printed JSON file
with open('financial_report.json', 'w') as out:
out.write(json.dumps(r.json(), indent=4))
I am getting a 200 response from my r object but when I go to dump the JSON data, here is my error:
https://www.screencast.com/t/ODMojS13WH
Has any one seen this before?
Is the response not a JSON object (which would be strange)?
Thank you in advance!
check if r.ok is True
check if r.json() returns json string. Use print statement.
Also r.text may be enough to write json to output file.
Example :
r = requests.get(URL, params={'limit': 200}, headers=HEAD)
print(r.json())
print(r.text())
Finance Reports Endpoint response content type is application/a-gzip, not application/json, so as you have commented, you have to decompress the binary content yourself.
However, there is a drawback in your code:
decompressed_data=zlib.decompress(r.content, 16+zlib.MAX_WBITS)
response.content triggers python-requests to load the content at once into memory, it could consume large amount of memory for large gzip responses.
Use response.raw file-like object and decompress data incrementally is more preferable. You can find example code here.
Or you can use applaud directly, it is a Python client library for accessing App Store Connect API. Your code can be shortened by using applaud:
import os
from applaud.endpoints.finance_reports import FinanceReportsEndpoint
from applaud.connection import Connection
KEY_ID = "XXXXXXXXXX"
ISSUER_ID = "XXXXXX-XXXXXXX-XXXXXX-XXXXXXX"
PATH_TO_KEY = os.path.expanduser('path/to/your/key.p8')
VENDOR_NUMBER = '12345678'
with open(PATH_TO_KEY, 'r') as f:
PRIVATE_KEY = f.read()
# Create the Connection
connection = Connection(ISSUER_ID, KEY_ID, PRIVATE_KEY)
r = connection.finance_reports().filter(
report_type=FinanceReportsEndpoint.ReportType.FINANCE_DETAIL, # or 'FINANCE_DETAIL'
region_code='Z1',
report_date='2021-03',
vendor_number=VENDOR_NUMBER
).get()
r.save('finance_reports.txt', decompress=True)
Full disclosure, I'm original author of applaud.

get a reuse the token for the Huawei modem E3372h

so i want to read some sms received in my huawei modem.
For that i m tryin to first get the token and session id from the 'http://192.168.8.1/api/webserver/SesTokInfo page
then try to reuse this token in the page http://192.168.8.1/api/sms/sms-list
but i got this error
<error>
<code>125002</code>
<message></message>
</error>
which mean that i don t have the right token value, what i m wondering about.
so this is how my code looks
import hashlib
import base64
import binascii
import xml.etree.ElementTree as ET
from datetime import datetime
import requests
from bs4 import BeautifulSoup
BASEURL = 'http://192.168.8.1'
session = requests.Session()
reqresponse = session.get(BASEURL + '/api/webserver/SesTokInfo')
if reqresponse.status_code == 200:
root = ET.fromstring(reqresponse.text)
for results in root.iter('SesInfo'):
sessionid = results.text
print("the sessionId is", sessionid)
for results in root.iter('TokInfo'):
token = results.text
print("The token is", token)
sessioncookies = reqresponse.cookies
post_data = '<?xml version = "1.0" encoding = "UTF-8"?>\n'
post_data += '<request><PageIndex>1</PageIndex><ReadCount>3</ReadCount><BoxType>1</BoxType><SortTyp$
headers = {'Content-Type': 'text/xml; charset=UTF-8',
'__RequestVerificationToken': token
}
api_url = BASEURL + '/api/sms/sms-list'
logonresponse = session.post( api_url, data=post_data, headers=headers, cookies=sessioncookies)
logonresponse2 = session.get( api_url, data=post_data, headers=headers, cookies=sessioncookies)
result = BeautifulSoup(logonresponse.text, 'html.parser')
for r in result:
print(r)
can someone helo me with the troubleshooting please?

Python Poloniex API Call

I have the following code that I am trying to make an API call to Poloniex according to their instructions
import urllib
import urllib.request
import json
import time
import hashlib
import codecs
import hmac
import time
Key = "whatever your key is"
Sign = "whatever your secret is"
def returnBalances(balances):
nonce = int(round(time.time()-599900000)*10)
parms = {"returnBalances":balances,
"nonce":nonce}
parms = urllib.parse.urlencode(parms)
hashed = hmac.new(b'Sign',digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Content-type":"application/x-www-form-urlencoded",
"Key":Key,
"Sign":signature}
conn = urllib.request.urlopen("https://poloniex.com")
conn.request("POST","/tradingApi",parms,headers)
response = conn.getresponse()
print(response.status,response.reason)
returnBalances('balances')
When I run this I get this error message
HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
Can someone please help?
You can catch HTTP errors with urllib.error.HTTPError
POST data should be bytes, so you have to encode parms
urllib.request.urlopen returns a HTTPResponse object, which has no request method.
If you want to set headers and other parameters you should use urllib.request.Request
According to the api docs the post parameters should be 'nonce' and 'command', so i modified your function to accept 'returnBalances' as a parameter and use it in parms["command"]
def api_call(command):
nonce = int(round(time.time()-599900000)*10)
parms = {"command":command, "nonce":nonce}
parms = urllib.parse.urlencode(parms).encode()
hashed = hmac.new(Sign.encode(), parms, digestmod=hashlib.sha512)
signature = hashed.hexdigest()
headers = {"Key":Key, "Sign":signature}
req = urllib.request.Request("https://poloniex.com/tradingApi", headers=headers)
try:
conn = urllib.request.urlopen(req, data=parms)
except urllib.error.HTTPError as e:
conn = e
print(conn.status,conn.reason)
return json.loads(conn.read().decode())
balances = api_call("returnBalances")

Resources