i am trying to create bill for payment and send to my customer via telegram bot:
i am using blockchain API V2-https://blockchain.info/api/api receive .my code is:
xpub='***'
keyk='02e57f1***'
url='https://api.blockchain.info/v2/receive?xpub='+str(xpub)+'&callback=https%3A%2F%2Fdoors03.ru&key='+keyk
x=requests.get(url)
r=x.json()
r=r['address']
r -is an adress wich was made.
i am sending it to my costumer(by the way is there any way to send adress with exact sum for pay ) . After i want to check is payment was recieved:
data={ "Content-Type": "text/plain","key":keyk,"addr":r,"callback":"https%3A%2F%2Fdoors03.ru","onNotification":"KEEP", "op":"RECEIVE"}
r = requests.post(url, data=data)
and this is the response - u'{\n "message" : "Internal handlers error"\n}'
what i am doing wrong ? how to check payments ? how to send address with exact sum of btc or ethereum ?
Sorry, i don't have enough reputation to post a comment, so this is
the only option i have. #egorkh have you solved this problem? Maybe
you have received explanation from blockchain.info support? I have
sent them a question about that, but they are answering for too long.
UPDATE: Finally, i have found solution.
In my case, reason of "Internal handlers error" message is in a wrong interpretation of their API.
As they haven't implemented balance_update request in their java-api, i did it on my own and i did it in wrong way.
I have put this parameters:
{"key":keyk,"addr":r,"callback":"https%3A%2F%2Fdoors03.ru","onNotification":"KEEP", "op":"RECEIVE"}
as post parameters, like in other methods they have provided in api. In those methods parameters are URLEncoded like you did with callback link. But...
In this HTML request they must be sent as plain text in json format without any special encoding, like that:
Map<String, String> params = new HashMap<String, String>();
params.put("addr", address);
params.put("callback", callbackUrl);
params.put("key", apiCode);
params.put("onNotification", keepOnNotification? "KEEP" : "DELETE");
params.put("confs", Integer.toString(confirmationCount));
params.put("op", StringUtils.isBlank(operationType) ? "ALL" : operationType);
//parse parameters map to json string(that's optional: you can write it directly as string)
String body = new Gson().toJson(params);
if (requestMethod.equals("POST")) {
byte[] postBytes = body.getBytes("UTF-8");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("Content-Length", String.valueOf(postBytes.length));
conn.getOutputStream().write(postBytes);
conn.getOutputStream().close();
}
The main reason of your error may be that you put "Content-Type": "text/plain" in data object (, and maybe encoded callback url) .
Related
I'm having trouble adding a Compliance Standard to an existing Policy via the Pal Alto Prisma Cloud API.
Everytime I send the request, I'm returned with a 500 Server Error (and, unfortunately, the API documentation is super unhelpful with this). I'm not sure if I'm sending the right information to add a compliance standard as the API documentation doesn't show what info needs to be sent. If I leave out required fields (name, policyType, and severity), I'm returned a 400 error (bad request, which makes sense). But I can't figure out why I keep getting the 500 Server Error.
In essence, my code looks like:
import requests
url = https://api2.redlock.io/policy/{policy_id}
header = {'Content-Type': 'application/json', 'x-redlock-auth': 'token'}
payload = {
'name': 'policy_name',
'policyType': 'policy_type',
'severity': 'policy_severity',
'complianceMetadata': [
{
'standardName': 'standard_name',
'requirementId': 'requirement_ID',
'sectionId': 'section_id'
}
]
}
response = requests.request('PUT', url, json=payload, header=header)
The response should be a 200 with the policy's metadata returned in JSON format with the new compliance standard.
For those using the RedLock API, I managed to figure it out.
Though non-descriptive, 500 errors generally mean the JSON being sent to the server is incorrect. In this case, the payload was incorrect.
The correct JSON for updating a policy's compliance standard is:
req_header = {'Content-Type':'application/json','x-redlock-auth':jwt_token}
# This is a small function to get a policy by ID
policy = get_redlock_policy_by_ID(req_header, 'policy_ID')
new_standard = {
"standardName":"std-name",
"requirementId":"1.1",
"sectionId":"1.1.1",
"customAssigned":true,
"complianceId":"comp-id",
"requirementName":"req-name"
}
policy['complianceMetadata'].append(new_standard)
requests.put('{}/policy/{}'.format(REDLOCK_API_URL, policy['policyId']), json=policy, headers=req_header)
I have written the following function in Python3.7 to generate x-instagram-gis. According to my research regarding this topic I have gathered that I only need the rhx_gis and variables (id: profile_id, first: int<50, after: end_cursor) to generate the x-instagram-gis.
def generate_x_instagram_gis(rhx_gis, cursor, profile_id):
params = {
"id": profile_id,
"first": 12,
"after": cursor,
}
json_params = json.dumps(params, separators=(',', ':'))
values = "{}:{}".format(rhx_gis, json_params)
return hashlib.md5(values.encode('utf-8')).hexdigest()
Running the following should return: 90bd6b662f328642477076d92d599064
rhx_gis = "7733066781d53e86a089eeb454c5446d"
cursor = "QVFBZWRqS0RnbGMtaXJhQzhlRW01R0I2YngtVXNQOGRTZzdHZEdseGcyVE1MdUxFYmYyY011Zkx6dFZtQUlsYWNvRl9DWnhtalpXZ2daSU5YQnFNTFBGRg=="
profile_id = "6822549659" #https://www.instagram.com/kimimatiasraikkonen/
print(generate_x_instagram_gis(rhx_gis, cursor, profile_id))
But it returns: f5e1e4be6612701d43523d707e36672b
For reference, these are the sources I've looked at:
https://github.com/rarcega/instagram-scraper/issues/205
How to perform unauthenticated Instagram web scraping in response to recent private API changes?
I'm not entirely sure what I'm doing incorrectly, when I run this with my entire program it doesn't work and this is the only part which causes an issue after much testing. Another thing I noted is that the MD5 is different when running on Python3.7 and Python2.7
I have figured it out.
The rhx_gis value is calculated based on the user-agent sent in the headers. The rhx_gis value I was obtaining was retrieved using python requests which sets its own user-agent (python-requests or something similar), whereas the rhx_gis value I was seeing on Postman was created using a different user-agent (set on Postman)
To fix this issue I had to set the same user-agent in python requests as the one set on Postman.
headers = {
'User-Agent' : '' # user-agent here
}
requests.get(url, headers=headers)
It seems that Instagram updated the API again, and a format for query_variable is changed. It looks like as follow:
{
"id":"25025320",
"include_reel":true,
"fetch_mutual":false,
"first":13,
"after":"QVFDZV9udFJKbVk3OGNlOE1LeGx3V1g0aEUyNFNSQTFUenhWOFVkWktTVzdpdUJRSk9EQXY3Ym9QQXFwTWJEci1pYklhSHFGQU1PTnl6QmhZbGpjalplSQ=="
}
I am learning how web apps work and after successfully creating connection between front and back end I managed to perform get request with axiom:
Route in my Flask
#app.route('/api/random')
def random_number():
k = kokos()
print(k)
response = {'randomNumber': k}
return jsonify(response)
my kokos() function
def kokos():
return (890)
Function that I call to get data from backend:
getRandomFromBackend () {
const path = `http://localhost:5000/api/random`
axios.get(path)
.then(response => {this.randomNumber = response.data.randomNumber})
.catch(error => {
console.log(error)
})
}
Now suppose I have an input field in my App with value that I want to use in the function kokos() to affect the result and what is going to be displayed in my app.. Can someone explain me how to do that?
Is this what POST requests are for and I have to post first and then get? Or can I use still GET and somehow pass "arguments"? Is this even GET and POST are for or am I making it too complicated for myself?
Is this the proper way to do these kind of thing? I just have a lot of code in python already written and want to simply exchange data between server and client.
Thank you, Jakub
You can add second argument
axios.get(path, {
params: {
id: 122
}
})
.then ...
You can pass id like this or anything it will be available in get params at python side like we pass in URL.
python side [Flask] (http://flask.pocoo.org/docs/1.0/quickstart/#accessing-request-data)
To access parameters submitted in the URL (?key=value) you can use the args attribute:
def random_number():
id = request.args.get('id', '')
k = kokos(id)
id will be passed kokos function if no id is provided it will be blank ''
you can read axios docu to make complex requests.
https://github.com/axios/axios
if any doubt please comment.
This may be the basic question but i am unable to investigate the issue. Need your help if anyone experience it.
During creation of NSURLRequest, i am setting handle cookies property to true.
urlRequest.HTTPShouldHandleCookies=true
When login response comes, we are saving cookies; Please have a look at code:
//Stored the cookies in shared place
let allHeaderFileds = httpResponse.allHeaderFields as! [String : String]
let cookies: NSArray? = NSHTTPCookie.cookiesWithResponseHeaderFields(allHeaderFileds, forURL: (response?.URL)!)
if let _ = cookies
{
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies! as! [NSHTTPCookie], forURL: (response?.URL)!, mainDocumentURL: nil)
}
When we are making another API call in which we need those cookies, we are also setting it here like following:
let cookieProperties:NSDictionary = [
NSHTTPCookieName:cookie.name!,
NSHTTPCookieValue:cookie.value!,
NSHTTPCookieDomain:cookie.domain!,
NSHTTPCookiePath:cookie.path!
]
let cookie:NSHTTPCookie = NSHTTPCookie(properties: cookieProperties as! [String : AnyObject])!
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
When i hit an API call to get data, it returns status code 403 and Message “Authentication credentials were not provided.”
For more details about header, please look into this:
"<NSHTTPURLResponse: 0x7fb5227444a0> { URL: http://172.16.10.249:8001/api/v1/users/profile/ } { status code: 403, headers {\n Allow = \"GET, POST, HEAD, OPTIONS\";\n \"Content-Type\" = \"application/json\";\n Date = \"Thu, 28 Jan 2016 10:22:22 GMT\";\n Server = \"WSGIServer/0.1 Python/2.7.11\";\n Vary = \"Accept, Cookie\";\n \"X-Frame-Options\" = SAMEORIGIN;\n} }"
Please let me know if i am wrong at any point or we need some extra configuration on iOS9. If server need to do some more steps please also mention it. Our server is written in Python.
I'm trying to remove invalid GCM Tokens from my database after they failed in a broadcast request.
I send it via:
payload = {
"registration_ids": gcm_keys,
"data": messageData
}
headers = {
'Content-type': 'application/json',
'Authorization': Message_Broker.api_key
}
try:
return requests.post(Message_Broker.host, data=json.dumps(payload), headers=headers)
Lets say I try to send a message to:
gcm_keys = ['daöodaeöoijiö','12345','fwiorjpfwj'] # Lets pretend the second one is a valid token
From the content of the response object I get a dict like this:
response_results = [{u'error': u'InvalidRegistration'}, {u'registration_id': u'1234567', u'message_id': u'0:14339323424213768%540eeb39f9fd7aed'}, {u'error': u'InvalidRegistration'}]
To find out which tokens failed I made a set substraction with a list comprehension:
failed_keys = list(set(gcm_keys) - set([r.get('registration_id') for r in response_results]))
This should give me back only the tokens which produced an error.
My first question is, is there a more common way to do so or any kind of best practice?
Second question is, as you can see in the response_results and the gcm_keys, the valid token is not returned. Instead a kinda similar token is given back.
I did not find any on this. Why do I get a different token back?
-> Just found out that in case I get a different token back, I should replace the old one. That leads to another question. When I send to several tokens, how can I find out to which gcm token in the request this returned token belongs?
Is the order in the results always the same as in the request?
The response body's results parameter should have an array of objects that are listed in the same order as the request. Please refer here.