I have a problem with the session ID http request - python

when I use the session code with the request in python it works but in php it tells me that it is invalid but when I take the session code from python and put it in php it works!
Or in other words, the session ID that I fetch through a request works, but in php it does not work
The function I used in Python:
def getSession():
url='https://ex.com'
data={
'session_id':'',
'campaign_id':'57430',
'embedded':'true',
'attribution_data':'',
'fund':'',
'amount':'1',
'frequency':'once',
'team':'',
'member':'',
}
r=post(url,data=data).json()['session']['id']
return r
The function I used in PHP:
function getSession(){
$url="https://ex.com";
$request=curl_init($url);
$data=http_build_query([
'session_id'=>'',
'campaign_id'=>'57430',
'embedded'=>'true',
'attribution_data'=>'',
'fund'=>'',
'amount'=>'1',
'frequency'=>'once',
'team'=>'',
'member'=>'',
]);
curl_setopt_array($request,[
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>$data,
CURLOPT_HTTPHEADER=>['Accept:application/json','Content-Type: application/x-www-form-urlencoded'],
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_COOKIESESSION=>TRUE
]);
The two perform the same purpose and they fetch the session id successfully, but the problem is that the id I get from Python only works and the one I get from php tells me it is expired!

Related

How to correctly generate x-instagram-gis

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=="
}

Axiom and Flask POST and GET requests, passing arguments

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.

Blockchain info wallet check payment

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) .

Uploading an image using the Python Etsy API

I am trying to upload an image to Etsy through the API. However, the example on their website is given in PHP which I don't know how to code. I only know how to work with Python. On their website it says:
Image uploads can be performed using a POST request with the Content-Type: multipart/form-dataheader, following RFC1867.
Their example which is in PHP
// You must define the constants OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET
// You must also assign values to the variables $access_token, $access_token_secret,
// $listing_id and $filename, and $mimetype.
// Your image file is assumed to be in the same directory as this code.
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
$oauth->enableDebug();
$oauth->setToken($access_token, $access_token_secret);
try {
$source_file = dirname(realpath(__FILE__)) ."/$filename";
$url = "https://openapi.etsy.com/v2/listings/".$listing_id."/images";
$params = array('#image' => '#'.$source_file.';type='.$mimetype);
$oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST);
$json = $oauth->getLastResponse();
print_r(json_decode($json, true));
} catch (OAuthException $e) {
// You may want to recover gracefully here...
print $oauth->getLastResponse()."\n";
print_r($oauth->debugInfo);
die($e->getMessage());
}
In API doc it says
HTTP Method = POST
URI = /listings/:listing_id/images
This is what I have so far in Python:
client_secret=client_secret,resource_owner_key=resource_owner_key,resource_owner_secret=resource_owner_secret)
url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'2343432434', 'images': :('test1.jpg', open('test1.jpg', 'rb'), 'image/jpeg')}
result = etsy.post(uri, params=payload)
When I run this code I get an 403 error. How can I fix my code so that it functions correctly? I have looked at other examples and just can't seem to make it work.

SoftLayer API Nessus Scan Status / Report via python

I want to use python client to create a Nessus Security Scanner and check the status by getStatus and get the result by getReport method. While, I have read these helps by php(SoftLayer API Nessus Scan Status / Report via PHP). But how can i use these by python client?
When I call setInitParameter(scan_id) in by python, the exception as flows:
SoftLayerAPIError(Client): Function ("setInitParameter") is not a valid method for this service
i recomend you to read documentation of the client first:
https://github.com/softlayer/softlayer-python
https://softlayer-api-python-client.readthedocs.io/en/latest/
the init parameters are set like this:
clientService.getObject(id=myInitParameter)
here you can find more examples using the client:
https://softlayer.github.io/python/
Here you can find additional documentation:
http://sldn.softlayer.com/blog
And renember that with the Softlayer's python client unlike the php client the data are sending in json format so the request:
$client = SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);
$accountInfo = $client->getObject();
$hardware = $client->getHardware();
foreach ($hardware as $server){
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey)
$scantemplate = new stdClass();
$scantemplate->accountId = $accountInfo->id;
$scantemplate->hardwareId = $server->id;
$scantemplate->ipAddress = $server->primaryIpAddress;
try{
// Successfully creates new scan
$scan = $scanclient->createObject($scantemplate);
} catch (Exception $e){
echo $e->getMessage() . "\n\r";
}
would be like this:
clientAccount = client['SoftLayer_Account']
accountInfo = clientAccount.getObject() #for this case we do not need init parameter
hardware = clientAccount.getHardware() #for this case we do not need init parameter
for server in hardware:
scanclient = client['SoftLayer_Network_Security_Scanner_Request']
scantemplate = {
"accountId": accountInfo["id"],
"hardwareId": server["id"],
"ipAddress": server["primaryIpAddress"]
}
scanclient.createObject(scantemplate)

Categories

Resources