I am submitting some data from website1 to website2 using curl.
When I submit data via then on receiving end I get it like
Array
(
[ip] => 112.196.17.54
[amp;email] => test#test.com
[amp;user] => test123,
[amp;type] => point
[amp;password] => password
)
According to me http_build_query() producing wrong results.
"ip" field is correct rest are incorrect.
Please let me know why it happens.
curl function is given below: http_build_query($config)
function registerOnPoints($username ,$password,$email,$ip , $time )
{
$ch = curl_init("http://website2c.com/curl-handler");
curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, 1);
$config = array( 'ip' => $ip,
'user' => $username,
'email' => $email,
'password'=> $password,
'time' => $time,
'type' => 'point') ;
# add curl post data
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($config));
curl_setopt($ch, CURLOPT_POST, true);
# execute
$response = curl_exec($ch);
# retreive status code
$http_status = curl_getinfo($ch , CURLINFO_HTTP_CODE);
if($http_status == '200')
{
$response = json_decode($response);
} else {
echo $http_status;
}
// Close handle
curl_close($ch);
}
If it is php version issue then, clearly speaking I have no permission to change the version of php because only the curl function is producing error rest project is completed and working as expected.
Please help me.
i guess you could try:
http_build_query($config, '', '&');
Or alternative:
$paramsArr = array();
foreach($config as $param => $value) {
$paramsArr[] = "$param=$value";
}
$joined = implode('&', $paramsArr);
//and use
curl_setopt($ch, CURLOPT_POSTFIELDS, $joined);
Related
I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);
I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
I’m struggling with the new MailChimp API and the batch functionality, specifically, how to return any errors from the underlying operations that were batched, not the batch operation itself.
My code is below and works to add the two test subscribers. The response only shows success for the overall batch:
[errored_operations] => 0
If I run it again, it will return a similar response, but with two errors:
[errored_operations] => 2
Other than that, there is no indication as to what failed or why. In this case, we know that it’s because the users are already subscribed. If I try to add a single user without the batch call, using POST /lists/{list_id}/members, I get a response that details exactly what failed.
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Member Exists
[status] => 400
[detail] => mary#jackson.net is already a list member. Use PUT to insert or update list members.
[instance] =>
)
How can I capture individual errors when adding (or updating or deleting) hundreds of subscribers?
I have tried just looping through users, making multiple individual calls, and that works: it adds the users and/or provides detailed error reporting. But it seems goofy to make 500 calls when the API is set up to handle this in a single call. Thanks for any ideas!
Here is my code:
$list_id = 'xyz123';
$subscribers = array(
array(
'email' => 'jeff#jackson.net',
'status' => 'subscribed',
'firstname' => 'Jeff',
'lastname' => 'Jackson'
),
array(
'email' => 'mary#jackson.net',
'status' => 'subscribed',
'firstname' => 'Mary',
'lastname' => 'Jackson'
)
);
$add_subs_batch = add_subs_batch($list_id, $subscribers);
echo '<pre>add_subs_batch: ';
print_r($add_subs_batch);
echo '</pre>';
function add_subs_batch($list_id, $data) {
$method = 'POST';
$batch_path = 'lists/' . $list_id . '/members';
$result = mc_request_batch($method, $batch_path, $data);
if($result && $result->id) {
$batch_id = $result->id;
$batch_status = get_batch_status($batch_id);
return $batch_status;
}
else {
return $result;
}
}
function get_batch_status($batch_id, $i=1) {
$method = 'GET';
$target = 'batches/'.$batch_id;
$result = mc_request($method, $target, $data);
sleep(1); // wait 1 second and try
if($result->status == 'finished' ) {
return $result;
}
else {
return get_batch_status($batch_id, $i+1);
}
}
function mc_request_batch( $method, $batch_path, $data = false ) {
$api_key = '12345-us1';
$dataCenter = substr($api_key,strpos($api_key,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/';
$target = 'batches';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $target );
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if( $data ) {
$batch_data = new stdClass();
$batch_data->operations = array();
foreach ($data as $item) {
$batch = new stdClass();
$batch->method = $method;
$batch->path = $batch_path;
$batch->body = json_encode( array(
'email_address' => $item['email'],
'status' => $item['status'],
'merge_fields' => array(
'FNAME' => $item['firstname'],
'LNAME' => $item['lastname']
)
) );
$batch_data->operations[] = $batch;
}
$batch_data = json_encode($batch_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $batch_data );
$response = curl_exec( $ch );
}
curl_close( $ch );
return json_decode($response);
}
You will get an id in response of the batch operation. This is 'Batch ID' which is a string that uniquely identifies the batch request.
To get the status of a batch request, you have to call a GET request to the URL, /batches/{batch_id}.
From the response, you can find a URL in response_body_url field which has the gzipped archive of the results of all the operations in the batch call.
Reference:
http://developer.mailchimp.com/documentation/mailchimp/reference/batches
http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/
Note
For security reasons, response_body_url is only valid for 10 minutes.
After 10 minutes, generate another with a GET call to
/3.0/batches/{batch_id}.
After you make the batch operation request, results are available for
7 days.
i'm trying to invite a person via email to Trello from my website. Here is the API reference. When I try to invite him, the plain reply is "invalid key". Here is my function:
public function inviteEmployeeToTrello ($email, $name, $isAdmin)
{
$organazationTrelloID = 'myOrganazationID';
$trelloAuthToken = 'myTrelloAuthToken';
$trelloInviteUrl = 'https://trello.com/1/organizations/'.$organazationTrelloID.'/members';
if ($isAdmin == 1)
{
$type = 'admin';
}
else
{
$type = 'normal';
}
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,
'token' => $trelloAuthToken
);
// open connection
$ch = curl_init();
// set the url, number of PUT vars, PUT data
curl_setopt($ch, CURLOPT_URL, $trelloInviteUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// exec
$replyRaw = curl_exec($ch);
$reply = json_decode($replyRaw, true);
// close connection
curl_close($ch);
dd($ch);
}
CURLOPT_POSTFIELDS does not want a JSON,
if you want a urlencoded request, use http_build_query($fields) , or if you want a multipart/form-data request, just give it $fields array directly. (the API doc's doesn't seem to mention which request types it accept, though. urlencoded is the most common one.)
As the error code says, you forgot to pass your application key. Here's an example from the API reference :
https://api.trello.com/1/organizations/publicorg?members=all&member_fields=username,fullName&fields=name,desc&key=[application_key]&token=[optional_auth_token]
You have to include it in your query, hence in your case, add it to the
$fields array :
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,,
'key' => $trelloAppKey
'token' => $trelloAuthToken
);
I am trying to implement transdirect.com shipping set sender API to my website but i am getting error i don't know what is the main cause of it.
here is the snippet::
$params = array(
'session' => $session,
'postcode' => '2164',
'name' => 'abc',
'company'=>'abc',
'email' => $email ,
'phone' => '4561237',
'streetName' => 'abcStreet',
'streetNumber' => '28',
'streetType' => 'St',
'suburb' => 'JHONFEILD',
'state' => 'NSW',
'pickupDate' => date( 'Y-m-d' ),
'pickupTime' => '1-4pm',
'hydraulicGate' =>'false'
);
$query = http_build_query($params);
$query = 'http://transdirect.com.au/api/v2/booking/sender?'.$query;
$result = json_decode( curl_sender( $query, $session, $email, $arg = 'sender') );
// curl_sender method::
function curl_sender( $url, $session, $email, $arg ) {
if ( $arg == 'sender' ) {
$datastring = "postcode=2164&name=Tara Trampolines&company=abc&email=".$email."&phone=0280049375&streetName=Unit 4/28 Victoria St&streetNumber=28&streetType=St&suburb=SMITHFIELD&state=NSW&pickupDate". date( 'Y-m-d' )."&pickupTime=1-4pm&hydraulicGate=false";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data1 = curl_exec( $ch );
curl_close( $ch );
return $data1;
}
I am getting:
stdClass Object (
[message] => Must be authenticated-please create a session first.
[code] => 403
)
Here is the link from we have implemented the api::
http://transdirect.com.au/api/v2/documentation
please specify how we can authenticate each method.
Any help will be appreciable, Thanks in advance.
You've to create a valid session before you requesting the API.
Create the session:
$credentials = array(
'email' => 'test#example.com',
'password' => 'secret'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Take a look at the session part: http://transdirect.com.au/api/v2/documentation
You can't mix the session creation process and the real API request.
Create session
Create API request with this session from step 1.
I'm not sure but I think you don't have to use the valid session as any parameter.
The documentation says only create a valid session, there is no parameter specified to append the session, so creation is maybe enough.
This is maybe very important for you:
Confirm booking with any special instructions etc. Once the booking is
confirmed your session is cleared and you will need to
re-authenticate.