Json Code Validation Error Curl Post Request - php

I am getting following JSON output using curl in PHP
CURL:
$request = curl_init("{$config['root']}/api/tickets");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($request, CURLOPT_TIMEOUT, 30);
add_headers($request);
$response = curl_exec($request);
Function:
function add_headers($request) {
global $config;
$headers = array('Content-Type: application/json');
if (empty($config['accessClient'])) {
curl_setopt($request, CURLOPT_USERPWD, "{$config['user']}:{$config['password']}");
} else {
array_push($headers, "Access-Client-Token: {$config['accessClient']}");
}
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
}
Output:
"{"amount":"100","description":"A ticket of 100.","payer":null,"successUrl":"http:\/\/localhost\/wordpress5\/ticket-confirmed.php","successWebhook":"http:\/\/localhost\/wordpress5\/ticket-confirmed-webhook.php","cancelUrl":"http:\/\/localhost\/wordpress5\/shop","orderId":"OID-1","expiresAfter":{"amount":1,"field":"hours"},"customValues":{}}"
and curl response is "
"{"Code":"Validation"}"
Developer Console:
Malformed JSON Ouput
Note: Values got from NetBeans Variables.
When I check output from Json validator it gets invalid only because of double quotes in start and end of output that I think is not bad in php when we assign a json output into variable.
Test Cyclos API here. U: demo P: 1234

So it turned out to be an issue with the demo account they provide.
The error validation has this description on their documentation site: Input error. Either a validation error or the maximum allowed items was exceeded
I created a new account and it is working fine, below is the code that i am using:
function add_headers($request) {
global $config;
$headers = array('Content-Type: application/json');
if (true || empty($config['accessClient'])) {
curl_setopt($request, CURLOPT_USERPWD, "geeky:1234");
} else {
array_push($headers, "Access-Client-Token: {$config['accessClient']}");
}
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
}
$body = '{"amount":"100","description":"A ticket of 100.","payer":null,"successUrl":"http:\/\/localhost\/wordpress5\/ticket-confirmed.php","successWebhook":"http:\/\/localhost\/wordpress5\/ticket-confirmed-webhook.php","cancelUrl":"http:\/\/localhost\/wordpress5\/shop","orderId":"OID-1","expiresAfter":{"amount":1,"field":"hours"},"customValues":{}}';
$request = curl_init("https://demo.cyclos.org/api/tickets");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $body);
curl_setopt($request, CURLOPT_TIMEOUT, 30);
add_headers($request);
$response = curl_exec($request);
$response = json_decode($response);
var_dump($response);
I have hardcoded the URL and also changed the username to my demo one.
Thank You.

Related

Issuing with making a post request with php curl

I'm trying to make a post request with php using curl however the json is not getting delivered to the REST API. Here is my code. In the webservice all I get is null value. I'm not sure where I'm going wrong.
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
Webservice code:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
Check PHP: curl_errno
There's probably a problem connecting to the server, and it's probably in one of your $header. To find out more, you need to show (in production, LOG it) the curl error.
In the future, please try to include a complete code sample, rather than just snippets
Code added from PHP: curl_strerror
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// #todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
Figured out a way to make this work.
Replaced $email_json_data = $this->post('email_json_data');
with $email_json_data = file_get_contents("php://input");

How to Add Recipient to Sendgrid v3 API with PHP

What I'm looking to do is add a single recipient to sendgrid when they signup on my site. Once they're added, I will then email the user and add them to a list.
But I'm having trouble adding the user to Sendgrid.
Their documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Recipients-POST) says to add a user you need to POST their details here:
https://api.sendgrid.com/v3/contactdb/recipients
add_user_new($email);
function add_user_new($email) {
$url = 'https://api.sendgrid.com/v3/contactdb/recipients';
$params =array( array(
//'name' => 'this is a reserved field',
'email'=> 'info#domain.com'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer api_key_here");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;
}
This is the response I get, not sure what I'm missing. The error they say is because the JSON is invalidly formatted.
string(51) "{"errors":[{"message":"request body is invalid"}]}
This is what my JSON looks like:
{"name":"hello#test.com"}
Encode your $json_post_fields variable do in JSON format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_post_fields));

PHP: CURL sendgrid API V3 authorization

I need a lot of help with curl and sendgrid integration and I wanted to start with the curl statement shown below:
curl -X "GET" "https://api.sendgrid.com/v3/contactdb/recipients" -H "Authorization: basic key" -H "Content-Type: application/json"
Below script gives me an error "message":"request body is invalid"
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$headers = array(
'Authorization' => 'Basic xxxxxxx',
);
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt ($session, CURLOPT_POSTFIELDS, $headers);
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Eventually, I want to integrate the subscription system from my website to seamlessly update Sendgrid contact lists. If you think there are better ways to achieve this, please feel free to point it out to me as well. Thanks!
Based on your code, try this:
<?php
$url = 'https://api.sendgrid.com/v3/templates';
$request = $url.'/user/profile';
$params = array(
'name' => 'test'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
?>
Also when trying to debug these kind of API integrations I find it very useful to bind cURL to a local proxy that way I can monitor the HTTP communication between cURL and the API, e.g.,
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
If your using Windows and testing locally Fiddler works great for that.
Here's my solution. It is based off too many sources to list.
define("SENDGRID_API_KEY","SG.xxxxxxxxxxxxxxxxxxxxxxxx");
//the 'to' parameter can be either be a single email as a string or an array of emails
function email($to,$subject,$message) {
if (!$to) return;
//start the params
$params=[
'from'=> "yourEmail#address.com",
'fromname'=> "Your From Name",
'subject'=> $subject,
'text'=> preg_replace("/\n\s+/","\n",rtrim(html_entity_decode(strip_tags($message)))),
'html'=> $message,
];
//if we have an array of email addresses, add a to[i] param for each
if (is_array($to)) {
$i=0;
foreach($to as $t) $params['to['.$i++.']']=$t;
//just one email, can add simply like this
} else {
$params['to']=$to;
}
// Generate curl request
$session = curl_init('https://api.sendgrid.com/api/mail.send.json');
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.SENDGRID_API_KEY));
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//execute and obtain response
$response = curl_exec($session);
curl_close($session);
//no response at all. that's bad!
if (!$response) {
$errorMessage="SENDGRID SENT NO RESPONSE<br>";
} else {
$response=json_decode($response,true);
//wasn't a success
if ($response['message']!='success') {
$errorMessage="SENDGRID SENDING ERROR<br>Error(s): ".implode("<br>",$response['errors']);
}
}
//finish forming error message and save to log
if ($errorMessage) {
$errorMessage.="Subject: ".$subject."<br>To: ";
if (is_array($to)) {
$errorMessage.=implode(",",$to);
//just one email, can add simply like this
} else {
$errorMessage.=$to;
}
yourOwnLoggingFunction($errorMessage);
}
//show full response if needed
// print_r($response);
}
//send to one person
email("test#email.com","The Subject","<h1>The Body</h1><p>Goes here</p>");
//send to multiple people
email(["test1#email.com","test2#email.com"],"The Subject","<h1>The Body</h1><p>Goes here</p>");
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Solved & working version here

PUT Request via CURL

I'm trying to make an CURL PUT REQUEST, my code looks like:
public function assignProfile($token, $organizationId, $profileId)
{
//define enviroment and path
$host = enviroment;
$path = "/admin/organizations/".$organizationId."/users";
$data_string = '["'.$profileId.'"]';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$token.'',
'Content-Length: ' . strlen($data_string)
));
echo "<br>OK<br>";
// execute the request
$output = curl_exec($ch);
// return ID for a new case
$output = json_decode($output);
var_dump($output);
}
Each part looks correct, when I var_dump $path, $host, even $data_string looks correct. However var_dump() at the end throw just NULL
I expect I'm doing something wrong or missing something really important.
May I ask you for some advise?
Thanks
EDIT:
What i do with it:
// define
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);
I would start by making sure the URL you're making the request to actually works and returns a valid response, you can do so by using a simple REST client (like POSTMAN chrome extension for example)
If you do get a response back, try and see if it's indeed a valid JSON, if not, that could be why you're not getting anything back from json_decode (more on return values here: http://php.net/manual/en/function.json-decode.php)
Finally, It is suggested you add curl_close($ch) to the end of your code to make sure your release the curl handle.

how to send xml file to server backend using php? [duplicate]

This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.
Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.

Categories