HHenry
HHenry

Reputation: 43

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!

Upvotes: 0

Views: 6563

Answers (3)

rgbflawed
rgbflawed

Reputation: 2137

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'=> "[email protected]",
        '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("[email protected]","The Subject","<h1>The Body</h1><p>Goes here</p>");
//send to multiple people
email(["[email protected]","[email protected]"],"The Subject","<h1>The Body</h1><p>Goes here</p>");

Upvotes: 2

HHenry
HHenry

Reputation: 43

<?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

Upvotes: 1

t.gere
t.gere

Reputation: 21

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.

Upvotes: 2

Related Questions