PHP: CURL sendgrid API V3 authorization - php

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

Related

Json Code Validation Error Curl Post Request

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.

Send message button in facebook bot PAGE

good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.

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));

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.

Diigo API -- HTTP Basic Authentication Error over CURL in PHP for HTTPS

Hi I am trying to post data Using CURL in PHP to diigo bookmarking, I have tried through API, When i executing file i got HTTP basic authentication here is my code
require_once('libs/diigo.class.php');
$diggo = new DiigoAPI("username","password");
$book = $diggo->getBookmarks();
$diggo->saveBookmarks("http://www.example.com");
public function saveBookmarks($url)
{
$attachment = array ("url" => $url, "title" => "SEnthil" , "shared" => "yes" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://secure.diigo.com/api/v2/bookmarks');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
echo $result;
curl_close ($ch);
}
Your curl doesn't have basic HTTP authentication set. You should set it up this way:
curl_setopt($curl, CURLOPT_USERPWD, $user_here . ":" . $password_here );
And the way you're doing it now the saveBookmarks function doesn't require the Diigo Class at all.

Categories