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));
Related
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.
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
When I'm posting json data to API using curl - I'm not getting any output. I would like to send email invitation to recipient.
$url_send ="http://api.address.com/SendInvitation?";
$str_data = json_encode($data);
function sendPostData ($url, $post) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
return curl_exec($ch);
}
And here is JSON $str_data
[
{
"authorizedKey" : "abbad35c5c01-xxxx-xxx",
"senderEmail" : "myemail#yahoo.com",
"recipientEmail" : "jaketalledo86#yahoo.com",
"comment" : "Invitation",
"forceDebitCard" : "false"
}
]
And calling function:
$response = sendPostData($url_send, $str_data);
This is the API: https://api.payquicker.com/Help/Api/POST-api-SendInvitation
Try adding curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
And changing http_build_query($post) to $post
The implementation:
<?php
$data = array(
"authorizedKey" => "abbad35c5c01-xxxx-xxx",
"senderEmail" => "myemail#yahoo.com",
"recipientEmail" => "jaketalledo86#yahoo.com",
"comment" => "Invitation",
"forceDebitCard" => "false"
);
$url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
The response I get is:
{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"}
But maybe it will work with valid data....
Edit:
For posting xml,
it's the same as on their site, except in a string:
$xml = '
<SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models">
<authorizedKey>80c587b9-caa9-4e56-8750-a34b17dba0a2</authorizedKey>
<comment>sample string 4</comment>
<forceDebitCard>true</forceDebitCard>
<recipientEmail>sample string 3</recipientEmail>
<senderEmail>sample string 2</senderEmail>
</SendInvitationRequest>';
Then:
sendPostData($url_send, $xml)
You have to add header:
$headers= array('Accept: application/json','Content-Type: application/json');
And:
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Otherwise ...
HTTP Status 415 - Unsupported Media Type
... may happen.
You don't need to add headers as you already do json_encode.
just print_r (curl_getinfo($ch)); and see the content type info in it.
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.
I'm working with the Google Translate API and there's the possibility that I could be sending in quite a bit of text to be translated. In this scenerio Google recommends to do the following:
You can also use POST to invoke the API if you want to send more data
in a single request. The q parameter in the POST body must be less
than 5K characters. To use POST, you must use the
X-HTTP-Method-Override header to tell the Translate API to treat the
request as a GET (use X-HTTP-Method-Override: GET). Google Translate API Documentation
I know how to make a normal POST request with CURL:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But how do I modify the header to use the X-HTTP-Method-Override?
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER
An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
Thus,
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
use the CURLOPT_HTTPHEADER option to add a header from a string array
Not enough for me , i need to use http_build_query fo my array post data
my full example :
$param = array(
'key' => 'YOUR_API_KEY_HERE',
'target' => 'en',
'source' => 'fr',
"q" => 'text to translate'
);
$formData = http_build_query($param);
$headers = array( "X-HTTP-Method-Override: GET");
$ch=curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$formData);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
$query = curl_exec($ch);
$info = curl_getInfo($ch);
$error = curl_error($ch);
$data = json_decode($query,true);
if (!is_array($data) || !array_key_exists('data', $data)) {
throw new Exception('Unable to find data key');
}
if (!array_key_exists('translations', $data['data'])) {
throw new Exception('Unable to find translations key');
}
if (!is_array($data['data']['translations'])) {
throw new Exception('Expected array for translations');
}
foreach ($data['data']['translations'] as $translation) {
echo $translation['translatedText'];
}
I found this help here https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/
Hope that helps