I have a php curl request which gives me a succesful response. I wanted to covert that in python.
define("uname", "myusername");
define("pwd", "password");
define("turl", "https://mytestapp.com/api/v1/");
$Params = array(
"subject" => "test subject",
"contents" => "This is a test case.",
"requester_id" => "2",
"channel" => "MAIL",
"channel_id" => "1"
);
$json = json_encode($Params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_URL, turl);
curl_setopt($ch, CURLOPT_USERPWD, uname.":".pwd);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
if($output=== FALSE) {
die(curl_error($ch));
}
curl_close($ch);
print_r(json_decode($output, true))
Tried with pycurl using same options of curl but it ended up with no use, it is giving a bad request error. I am unable to trace what is the error there.
import pycurl
import json
import urllib
params = [{"subject" : "test subject",
"contents" : "This is a test case.",
"requester_id" : "2",
"channel" : "MAIL",
"channel_id" : "1"
}]
json_to_send = json.dumps(params)
curlClient = pycurl.Curl()
curlClient.setopt(curlClient.FOLLOWLOCATION,True)
curlClient.setopt(curlClient.URL, url)
curlClient.setopt(curlClient.MAXREDIRS, 10)
curlClient.setopt(curlClient.USERPWD, "myusername:mypassword")
curlClient.setopt(curlClient.SSL_VERIFYPEER, False)
curlClient.setopt(curlClient.POSTFIELDS, json_to_send)
curlClient.setopt(curlClient.CUSTOMREQUEST, "POST")
curlClient.setopt(curlClient.POST, True)
curlClient.setopt(curlClient.FAILONERROR, True)
curlClient.perform()
Is there any better alternate to replicate same in python
Thanks in adavance
Related
Good day family !
Please help me using this API.
This API is user to get a token see the normal answer :
{'status': True, 'message': 'Success', 'code': 50, 'data': {'token': '773b718a53341b57zd511dazd4588fdf2', 'amount': 45.0}}
When i use Python it's working fine ! here is the python working code :
import requests
import json
headers = {"Authorization": "Token 12345678900987654321234567890", "Content-Type":"application/json"}
data = {"vendor": 1265,
"amount": 45,
"note" : "Commande #1324"
}
r = requests.post("https://sandbox.paymee.tn/api/v1/payments/create", data=json.dumps(data), headers=headers)
response = r.json()
# Now you can use
print(response)
But when i use PHP i have as output : NULL
Here is the code
<?php
$headers = array("Authorization: Token 12345678900987654321234567890");
$curl_post_data = array(
'vendor' => 1265,
'amount' => 45,
'note' => "Commande #1324"
);
$curl_handle=curl_init('https://sandbox.paymee.tn/api/v1/payments/create');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, true);
curl_se
topt($curl_handle, CURLOPT_POSTFIELDS, $curl_post_data);
$query = json_decode(curl_exec($curl_handle),true);
var_dump($query);
curl_close($curl_handle);
?>
Do you have any solution please ? i spent one week stuking there ! and my exam is close... :(
Thanks in advance
$result = curl_exec($curl_handle);
$query = json_decode($result,true);
<?php
$headers = array(
"Authorization: Token 12345678900987654321234567890",
"Content-Type: application/json"
);
$data = array(
"vendor" => 1265,
"amount" => 45,
"note" => "Commande #1324"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://sandbox.paymee.tn/api/v1/payments/create");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
print_r($response);
?>
This gives me the response that I'm using a invalid token which seems about right since you gave a sample token.
I'm trying validate url for comment form.
Then I thought ”Safe Browsing Lookup API” looked good.
However, the following code only returns an empty array in $result.
What can I do to improve this code?
code:
<?php
$api_key = 'xxx';
$url = 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' . $api_key;
$data = [
"client"=>[
"clientId" => "yourcompanyname",
"clientVersion" => "1.5.2"
],
"threatInfo"=>[
"threatTypes" =>["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes" =>["WINDOWS"],
"threatEntryTypes"=>["URL"],
"threatEntries" =>[
["url"=>"http://goooogleadsence.biz/"],
["url"=>"http://www.urltocheck2.org/"],
["url"=>"http://activefile.ucoz.com/"]
]
]
];
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
var_dump($result); // -> string(3) "{}"
curl_close($ch);
I am having issue while using cloudflare APIv4. Trying to update a dns record and not sure why am I receiving following error:
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9020,"message":"Invalid DNS record type"}]}],"messages":[],"result":null}
Here is the PHP function:
function updateCloudflareDNS($zone_id,$dns_id, $updatedata){
$updatedata = '[{"name":"**.****.com"},{"type":"A"},{"ttl":"1"},{"content":"8.8.8.8"},{"proxied":"true"}]';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".$zone_id."/dns_records/".$dns_id);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'X-Auth-Email: **********',
'X-Auth-Key: ***********'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $updatedata);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Also, I am putting record type "A" correctly as mentioned on the Cloudflare API documentation
Could someone help me out with this issue?
Thanks
You're sending a payload of:
[{"name":"**.****.com"},{"type":"A"},{"ttl":"1"},{"content":"8.8.8.8"},{"proxied":"true"}]
Here's what the API expects:
{"type":"A", "name":"example.com", "content":"127.0.0.1", "ttl":120, "priority":10,"proxied":false}
And this is how you properly construct JSON in PHP:
$POST = json_encode(array(
"type" => "A",
"name" => "...",
...
));
I am facing MALFORMED_REQUEST in paypal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"intent\":\"authorize\",
\"payer\":{
\"payment_method\":\"credit_card\",
\"funding_instruments\":[{
\"credit_card\":{
\"number\":\"5555555555554444\",
\"type\":\"mastercard\",
\"expire_month\":07,
\"expire_year\":22,
\"cvv2\":123,
\"first_name\":\"FName\",
\"last_name\":\"Lname\",
\"billing_address\":{
\"line1\":\"address,\",
\"city\":\"City\",
\"state\":\"state\",
\"postal_code\":\"postal_code\",
\"country_code\":\"country_code\"
}
}
}]
},
\"transactions\":[{
\"amount\":{
\"total\":\"10\",
\"currency\":\"CAD\",
\"details\":{
\"subtotal\":\"10\",
\"tax\":\"0\",
\"shipping\":\"0\"
}
}
}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer myAccessToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Here I am calling curl for authorization with paypal
jsonlint.com shows this json format is ok
But still I am getting response like,
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"9d7454a8637ae"}
Not getting exactly where I am wrong? Does any one know? Thanks in advance!
Your problem is the 07 in "expire_month": 07. I assume this value is meant to be a string. Not sure what you pasted in to jsonlint but it wasn't the JSON in your question.
As indicated in the comments, don't roll your own JSON. Use the tools available
$data = [
'intent' => 'authorize',
'payer' => [
'payment_method' => 'credit_card',
'funding_instruments' => [[
'credit_card' => [
'number' => '5555555555554444',
'type' => 'mastercard',
'expire_month' => '07',
'expire_year' => '22',
'hopefully you get the idea' => 'by now'
]
]]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
As the error indicates, your JSON is not formed correctly.You need not pass \ to escape your request parameters . Try removing those or try this sample code which works out of the box.
<?php
$data = 'response_type=token&grant_type=client_credentials';
$headers_arr = array();
$headers_arr[]="Accept-Encoding:application/json;charset=utf-8";
$headers_arr[]="Accept-Language:en_US";
// $headers_arr[]="Authorization:Bearer AZHFuBBAIG1rP98P7Svn2WOVatM5KAllu6KvrTE8GGT4gt9vdfj8TtR_1Cer:EBTMERCurtbf_4auykCeGWYGvwsy147bSb3xCuYpohmouVBGTaYFUIRwWgbx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "ARLg-BBMeTGLU5IHCsdIKEC_R_sMAkWM-yLsI5W5u9RuhvNhgolhYv-1cWmr:EJdAYxDx29McgMKOWjGK1OLHyaIxQBRuV9sWgfFSeMKGVBe-1jdiNgv5TLtP");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
$result = curl_exec($ch);
$res = json_decode($result);
$access_token = $res->access_token;
//now create a paypal payment
$headers_arr = array();
$headers_arr[]="Content-Type:application/json;charset=utf-8";
$headers_arr[] = "Authorization: Bearer $access_token";
// echo '<pre>';
// print_r($headers_arr);
$data_string = '{
"intent":"authorize",
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
"number":"4446283285273500",
"type":"visa",
"expire_month":11,
"expire_year":2018,
"cvv2":"874",
"first_name":"Betsy",
"last_name":"Buyer",
"billing_address":{
"line1":"111 First Street",
"city":"Saratoga",
"state":"CA",
"postal_code":"95070",
"country_code":"US"
}
}
}
]
},
"transactions":[
{
"amount":{
"total":"7.47",
"currency":"USD",
"details":{
"subtotal":"7.41",
"tax":"0.03",
"shipping":"0.03"
}
},
"description":"This is the payment transaction description."
}
]
}';
// echo data_string;
$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
curl_setopt($chs, CURLOPT_POST, true);
curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($chs, CURLOPT_TIMEOUT, 45);
curl_setopt($chs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs, CURLOPT_POST, 1);
curl_setopt($chs, CURLOPT_HTTPHEADER, $headers_arr);
if(curl_exec($chs) === false)
{
echo 'Curl error: ' . curl_error($chs);
}
$results = curl_exec($chs);
$res = json_decode($results);
echo 'ress=<pre>';
print_r($results);
I'm trying to POST using php. In the API it's suggested the following format.
// post url, keys are added here.
{
"EmailAddress": "john.smith#acmeconsulting.co",
"ActivityEvent": 112,
"ActivityNote": "Note for the activity",
"ActivityDateTime": "yyyy-mm-dd hh:mm:ss",
"FirstName": "John",
"LastName" : "Smith",
"Phone" : "+919845098450",
"Score": 10
}
My code in PHP :
$firstName='Test5';
$activityEvent=201;
$emailAddress='test10#test.com';
$activityNote='Note note note';
$phone='999999999';
$date='2015-07-21 12:48:10';
$data_string['ActivityEvent']=$activityEvent;
$data_string['EmailAddress']=$emailAddress;
$data_string['ActivityNote']=$activityNote;
$data_string['Phone']=$phone;
$data_string['ActivityDateTime']=$date;
//json_encode($data_string);
try
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length:'.strlen($data_string)
));
$json_response = curl_exec($curl);
curl_close($curl);
} catch (Exception $ex) {
curl_close($curl);
}
This code is not working as expected. I'm not getting any update there. Is the code correct?
Have you tried this?
$object = new StdClass;
$object->ActivityEvent = 201;
$object->EmailAddress = 'john.smith#acmeconsulting.co';
//add more properties here
echo json_encode($object);
$datastring = array(
'firstName' => 'John',
'lastName' => 'Smith',
...........);
$ch = curl_init("YOUR_URL_HERE");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
the result will be stored in the $result variable