I use Sendgrid to send emails. Emails are sent using their web API and I use an endpoint to get each email events.
Here is the code of this endpoint (that Sendgrid call each time when an event occur, after sending an email).
I would like to get the status code of each event (eg : 5.1.1 for a bounce).
Here is what I tried so far :
$data = file_get_contents("php://input");
$events = json_decode($data, true);
foreach ($events as $event) {
$sg_message_id = $event['sg_message_id']; //OKAY
$event = $event['event']; //OKAY (eg : "bounce")
$status = $event['status']; //NOT OKAY ("undefined index")
//and if I try :
$status = $event['event']['status']; //I get the first letter of the event (eg : "b" for bounce)
}
the documentation (here : https://sendgrid.com/docs/API_Reference/Webhooks/event.html, Bounce part) says there is a field "status" (eg : 5.1.1), and I don't understand why it doesn't work,
Any idea?
I understood the problem :
I tried to simulate a bounce error using a fake user email like
user#gmail1.com
but Sendgrid didn't process the email (host not reacheable) and returned a "dropped" event.
Instead, if I send an email to:
another-user-unknow#gmail.com
then sendgrid return a process event and then a bounce event, with the bounce status code:)
Related
The following code I am using to send mails from php.
<?php
require 'vendor/autoload.php';
$email->setFrom("test#example.com", "Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("test#example.com", "Example User");
$email->setOpenTracking(true, "--sub--");
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
$response = $sendgrid->send($email);
?>
Here I am setting Open Tracking for web-hook, When an email is opened the open event trigger and response coming to my given URL. Here I am getting web-hook every time when ever that email is opened by client. But I want Unique Open tracking.
I tried this which not working and may be invalid method:
$email->setUniqueOpenTracking(true, "--sub--");
Is there any setting or parameters That I need to configure.
Thanks in Advance
After call conversation with send grid, they are not providing Unique open tracking.
I have to maintain the opened web-hooks in a table and check every time, whether the web-hook is already received or not.
I am trying to send an (simple test) email when I receive an account.updated call for a custom account from Stripe API. My other webhooks to create charges and inform customers about successful or failed charges work like this, but here I get an error 500 (I can see that in the dashboard of the custom account) and the mail is NOT send, so I am not sure what I am doing wrong here. My code looks like this:
<?php
require_once('vendor/autoload.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_XXXX");
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
// Verify the event by fetching it from Stripe
$event = \Stripe\Event::retrieve($event_json->id);
// Do something with $event
if ($event->type == 'account.updated') {
// The E-Mail message to send to inform about a succeeded charge
$message = 'test';
// Send the E-Mail
mail('test#example.com', 'We need more info about you!', $message);
}
http_response_code(200); // PHP 5.4 or greater
Thank you for your help!
If you look at your web server's error.log (usually accessible from your hosting control panel or in /var/log/) do you see more detail on what's causing the 500?
Could it be $event = \Stripe\Event::retrieve($event_json->id); failing?
If the event is occurring directly on a connected account, you may also need to pass the account id to retrieve it.
See here for a bit more context,
https://stripe.com/docs/connect/webhooks
The code would be more like:
$event = \Stripe\Event::retrieve(
array("id" => $event_json->id),
array("stripe_account" => $event_json->account));
https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header
i am working with Facebook Checkbox Plugin everything is working fine except facebook is not sending request to my webhook url when Confirming Opt-in.
in facebook docs it is mentioned that
After the opt-in event, we will post a webhook event to your server if the checkbox state was checked. This callback has the same format as the opt-in callback, but instead of a sender field, it has an optin object with a user_ref field.
But it is not sending any data. here is my webhook code
if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] == 'subscribe' && $_REQUEST['hub_verify_token'] == 'verificationtoken') {
echo $_REQUEST['hub_challenge'];
}
$data = file_get_contents("php://input");
$fp = file_put_contents( PROTECH_FBB_DIR.'/data.log', $data);
i have also tried hitting my webhook manually and see if it responds. and it does work perfectly normal, so it means facebook is not posting data or maybe i am doing something wrong?
Any help would be highly appreciated. thanks
I am not php developer but have implemented the same logic in javascript, node.js. I would like to share the steps in detail and also the javascript code and hope you can figure out what you can do with it to make your life better :P
As you said, you are receiving the user_ref from the api call. That's correct. Read the documentation once again they have mentioned the user_ref will be received when user check the checkbox plugin. This user_ref is set by you and every-time the page loads this user_ref must be unique then only the checkbox plugin will render, if it is not unique the plugin wont render. And here is the complete logic behind it. You generate the user_ref, when user check the checkbox, you receive this unqiue user_ref, using this user_ref you send message to the user(you can send message to user using user_ref as many time as you want but I will suggest you rather use senderId). When you send the message to user using user_ref, the webhook api will give you a response containing senderId of the user which is actually psid we normally use in our app. This is what you need to save in your db.
Now I will put my code here how I did it.
Receiving the user_ref and sending message to user:
My payload:
function sendTextMessageRef(user_ref, messageText,md) {
var messageData = {
recipient: {
user_ref: user_ref
},
message: {
text: messageText,
metadata: md
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
}
Now, after sending the message, I receive a response in this json format which will include the sender id of the user:
{"sender":{"id":"xxxxxxx"},"recipient":{"id":"xxxxxWhat you are looking for is this*******"},"timestamp":1504698781373,"message":{"is_echo":true,"app_id":xxxxxxxxxxxxxxx,"metadata":"INVITATION__REPLY__qwe__2017-09-05T02xo20__xxxxxxxx__063__yes","mid":"mid.$cAAGcxxxxxxxxVxuAtJ","seq":120162,"text":":)"}}
In above received json data, the recipient.id is what you are looking for.
Here To make you understand what I did in my chat bot is first user select the checkbox plugin, I receive the call on my server, if check if it contains user_ref, if yes then I send a text message to user with a custom metadata using user_ref. When user receives the message, the webhook send me a json data in the above given format. To identify for which user_ref I have received this response, I set custom metadata which is combination of some string+user_ref. Using this I identify the sender.id of the user for which I previously sent message using user_ref. The sender.id is my pageid and recipient.id the the user id which you are trying to get and using which we generally send message to the user and is also know as psid.
Hope this helps, if you still get some issue using the above mentioned solution, then do update about it :)
i run php to send email list using third party smtp. I want to show Receipt(TO:) with my customer email. So i need to loop call php email function follow:
$emailList = explode("\n",file_get_contents('/list1.txt'));
foreach ($emailList as &$value) {
$email = new Email();
$email->setFrom("info#xxx.net");
$email->setToList($value);
$email->setSubject("360’s Got Talent");
$email->setHtmlContent($str);
$apiClient = new ApiClient("edm#xxx.net", "xxx");
$response = $turboApiClient->sendEmail($email);
var_dump($response);
echo ":: $value has been sent.<br />";
}
unset($value);
Is it standard way to do ?
Are there anyway to sent one time but can show TO: one by one ?
because when I run this, PHP is waiting total process and then writing report (echo). Sometime server is showing 504 Gateway Timeout.
or Can I make PHP run one by one ? report every line once it done, not waiting the whole process like a batch process.
Please guide.
I am sending emails via SendGrid with this inside the x-smtpapi header
$json_string = array(
'unique_args' => array (
'email_id' => 1
)
);
It all seems to send okay, inside SendGrid I can view the "email_id" in the Email activity under Unique Args.
However when I try to use the API to look at this email, I cannot find a way to actually get these unique arguments from the API.
I am using this to try and get the headers returned with the bounced emails.
$request = 'https://api.sendgrid.com/api/bounces.get.json&api_user=username&api_key=password'
All I get is just the email addresses that have bounced, not the header information (the unique arguments)
I want to know, is it possible to get the unique arguments from the API. I have read it multiple times to no avail.
I hope this makes sense.
Thanks
At present there's no way request to lookup specific events by unique_arg with the Web API.
However, the SendGrid Event Webhook will give you granular data on each event, such as a bounce as it happens. The Event Webhook POSTs data to your server every time an action is taken upon an email (e.g. open, click, bounce).
Once you receive it, you're responsible for storing this, although it's not a typical API it gives very specific data on events which you can then compile and rehash however you like.
To get started using the webhook, you'll do something like the following, and have SendGrid POST to the following script:
<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);
foreach ($events as $event) {
// Here, you now have each event and can process them how you like
process_event($event);
}
[Taken from the SendGrid Webhook Code Example]