I tried to add emails to an existing contact list in my sendgrid account using api php, but something went wrong in my code, which returns the following message:
{"traceback": "'Traceback (most recent call last): Failure: exceptions.ValueError: Test does not exist '", "error": "Test does not exist"}
and for the create campaign button, it returns this error :
{"errors":[{"field":null,"message":"authorization required"}]}
So, have you any idea of how to create this campaign in php ? Here is what I was trying :
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<title>Ajax - La fonction ajax()</title>
</head>
<body>
<?php
$url = 'https://api.sendgrid.com/';
$user = '******';
$pass = '********';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'hjhgfr3@gmail.com',
'subject' => 'Hello Girl !',
'html' => 'This is me ! :D',
'text' => 'Hello, Girl',
'from' => 'myemail@mydomain.com',
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
?>
<button id="action">add to list</button><br /><br>
<button id="action2">Create campaign </button>
<script>
$(function() {
$('#action').click(function() {
$.ajax({
type: 'GET',
url: 'https://api.sendgrid.com/api/newsletter/lists/email/get.json?api_user=******&api_key=********&list=Test&email@email.com',
/* timeout: 3000,*/
success: function(data) {
alert(data); },
error: function() {
alert('La requête n\'a pas abouti');
}
});
});
});
</script>
<script>
$("#action2").click(function() {
$.get("https://api.sendgrid.com/v3/campaigns?Authorization=Bearer+API-KEY",
{
"title": "March Newsletter",
"subject": "New Products for Spring!",
"sender_id": 124451,
"list_ids": [
110,
124
],
"segment_ids": [
110
],
"categories": [
"spring line"
],
"suppression_group_id": 42,
"custom_unsubscribe_url": "",
"ip_pool": "marketing",
"html_content": "<html><head><title></title></head><body><p>Check out our spring line!</p></body></html>",
"plain_content": "Check out our spring line!"
},
function(data, status){
alert("Data: " + data + "
Status: " + status);
});
});
</script>
</div>
Looks like there are a couple of issues.
You are not properly authorizing. You need to set an Authorization header in your api request. Check out the docs for more info on how: https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html .
I see you're making GET requests, GET in this case will only retrieve data and not let you create a campaign or add to a list. You need to use POST as mentioned in the docs, https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html
Also it might help to use an HTTP Client lib for PHP such as, HTTPFUL instead of using Curl, but whatever you prefer.