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
Related
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'm trying to submit a new paste to Paste.ee API using Curl, but the response is always Whoops, looks like something went wrong.
Here's the guideline of Paste.ee API: https://paste.ee/wiki/API:Basics
Here's how my simple code looks like:
<?php
$key = '56b3f127d65445c0cf6ff05f62ffba53';
$format = 'JSON';
$description = 'just for testing';
$paste = 'Just a simple test';
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://paste.ee/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("key" => $key, "format" => $format, "description" => $description, "paste" => $paste));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
} else {
error_log("You need cURL to use this api!");
}
?>
I've double-checked, my key is right.
I'm new to Curl, so any advice would be very appreciated.
Thanks.
It's because "format" is case sensitive in which it must small letters
You your format is capitalised which is it should be small letters
"format": "json"
look
$key = '56b3f127d65445c0cf6ff05f62ffba53';
$format = 'JSON';
$description = 'just for testing';
$paste = 'Just a simple test';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://paste.ee/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'key' => $key,
'format' => $format,
'description' => 'just for testing',
'paste' => $paste,
'format' => 'json'
));
CAPITALISED WHICH RETURNS ERROR
small letters which returns the correct json data
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
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 typically send an array of strings using CURL in PHP, something like this:
$data = array(
"key1" => $value,
"key2" => $value,
"key3" => $value,
"key4" => $value
);
Then, among other curl_setop settings, post using:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
This all works fine. But now in addition to those strings, I have 1 dataset that is JSON encoded and I want to post it at the same time. JSON looks like this:
Array ( [ad_info] => {"MoPubAdUnitInteractions":"a","MoPubAdUnitConversations":"b","MoPubAdUnitGroups":"c"} )
I think I figured out how to do it by setting a header saying I'm going to be passing in JSON like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
But then, can I simply add another line for the post, but in this case the JSON encoded value like this:
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
I'm kinda shooting in the dark, any suggestions on how I should be thinking about this?
Ok, here is the full example:
From Processing The Form Post:
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
);
$json_data = array("ad_info" => $community_ad_info);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null, $json_data);
And the Function in PHP I'm calling to do the CURL:
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
if ($json_data)
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
Any help is greatly appreciated.
You use wrong approach. Setting CURLOPT_POSTFIELDS option twice doesn't lead to result you expected since each setting call discards effect of previous one.
Instead of this, you have to append extra data ($community_ad_info) to the main POST data ($data) before passing it to CURLOPT_POSTFIELDS option.
...
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
...
This is untested of course but it should do what you need.
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
And now the actualy logic
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
The things to note here are,
the new content tyoe header tells it to be processed as a form post.
removal of the $json_data array, the "ad_info" key is not just added into the $data array
When you process this on the other side you can access the ad_info like this
$ad_info = json_decode($_POST['ad_info']);
You can access the other fields with
$apns_name = $_POST['apns_name'];