I am using AWS to send emails in my project.. I created subscription and done all the steps. Its sending emails to the user but the notification is not receiving.. it says notification failed. I don't know the reason.. but I am getting notifications if I use http url instead https url.
The php code I am using is added below -
<?php
require 'path/to/vendor/autoload.php';
use AwsSnsMessageValidatorMessage;
use AwsSnsMessageValidatorMessageValidator;
use GuzzleHttpClient;
// Make sure the request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die;
}
try {
// Create a message from the post data and validate its signature
$message = Message::fromRawPostData();
$validator = new MessageValidator();
$validator->validate($message);
} catch (Exception $e) {
// Pretend we're not here if the message is invalid
http_response_code(404);
die;
}
if ($message->get('Type') === 'SubscriptionConfirmation') {
// Send a request to the SubscribeURL to complete subscription
(new Client)->get($message->get('SubscribeURL'))->send();
} elseif ($message->get('Type') === 'Notification') {
// Do something with the notification
save_message_to_database($message);
}
I am following the AWS documentation. Do you know the reason.. is there any issue in this code?
Related
I'm working on a chat application using PubNub and PHP. The publishing of messages is working but I'm not sure how to read from the subscriber.
I ran the subscriber file in the command line and it is showing the messages as they are published but I'm not sure how to read from it or how to return, as per the doc the subscriber is a separate process.
use PubNub\PNConfiguration;
class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
function message($pubnub, $message) {
print_r($pubnub);
print_r($message);
}
function presence($pubnub, $presence) {
// handle incoming presence data
}
}
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
$pubnub->subscribe()
->channels(["Channel-1","Channel-2","Channel-3"])
->execute();
this is the subscriber code present on the PubNub Doc.
I'm calling this file using javascript.
I've posted this question twice in the last two days and I have really run dry of solutions. I'm creating a very simple comment box that when filled out sends the comment in an email to my company's safety department. I have been receiving this 5.5.4 Invalid Domain Error for the last couple days.
It's SMTP and TLS. The port and server name is correct. The server allows for anonymous emails, and does not validate. I'm using the Swiftmailer library so I shouldn't need to script a ELHO/HELO. The only property of the email that's not defined/hard coded is the body of the message. This is the code for my controller (index.php).
// Initialize Swiftmailer Library
require_once("./swiftmailer/lib/swift_required.php");
// Class that contains the information of the email that will be sent (from, to, etc.)
require_once("./classes/EmailParts.php");
// The class that "breaks" the data sent with the HTML form to a more "usable" format.
require_once("./classes/ContactForm.php");
// =====================
// Main Configuration
// =====================
define("EMAIL_SUBJECT", "Safety Concerns");
define("EMAIL_TO", "safetydepartment#company.com");
define("EMAIL_FROM", "safetydepartment#company.com");
// SMTP Configuration
define("SMTP_SERVER", 'exchange.company.local');
define("SMTP_PORT", 25);
function main($contactForm) {
// Checks if something was sent to the contact form, if not, do nothing
if (!$contactForm->isDataSent()) {
return;
}
// Validates the contact form and checks for errors
$contactForm->validate();
$errors = array();
// If the contact form is not valid:
if (!$contactForm->isValid()) {
// gets the error in the array $errors
$errors = $contactForm->getErrors();
} else {
// If the contact form is valid:
try {
// send the email created with the contact form
$result = sendEmail($contactForm);
// after the email is sent, redirect and "die".
// We redirect to prevent refreshing the page which would resend the form
header("Location: ./success.php");
die();
} catch (Exception $e) {
// an error occured while sending the email.
// Log the error and add an error message to display to the user.
error_log('An error happened while sending email contact form: ' . $e->getMessage());
$errors['oops'] = 'Ooops! an error occured while sending your email! Please try again later!';
}
}
return $errors;
}
// Sends the email based on the information contained in the contact form
function sendEmail($contactForm) {
// Email part will create the email information needed to send an email based on
// what was inserted inside the contact form
$emailParts = new EmailParts($contactForm);
// This is the part where we initialize Swiftmailer with
// all the info initialized by the EmailParts class
$emailMessage = Swift_Message::newInstance()
->setSubject($emailParts->getSubject())
->setFrom($emailParts->getFrom())
->setTo($emailParts->getTo())
->setBody($emailParts->getBodyMessage());
// Another Swiftmailer configuration..
$transport = Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_PORT, 'tls');
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($emailMessage);
return $result;
}
// Initialize the ContactForm with the information of the form and the possible uploaded file.
$contactForm = new ContactForm($_POST, $_FILES);
// Call the "main" method. It will return a list of errors.
$errors = main($contactForm);
// Call the "contactForm" view to display the HTML contact form.
require_once("./views/contactForm.php");
I've posted the entirety of my code at Dropbox. There's not much, but I think the problem must lie in the Index.
I am implementing twilio outgoing call with wordpress woocommerce. As soon as the order is placed the site owner will receive a call. However i couldn't find a way to handle if the person didn't answer the call for some reason. The documentation is going above my head.
What i want is to make twilio recall if the call isn't answered. Or i am open to suggestion how else would be the good way to handle. Please note that i have not created any application at Twilio yet. Just using the PHP SDK as the account id and token is provided by default.
here is the code
function send_order_Call($order_id) {
try {
$file = plugin_dir_path(__FILE__) . "order.xml";
$twiML = simplexml_load_file($file);
$twiML->Say = "Hello, You have received a new order. The order id is {$order_id}. Kindly check you fax for details";
file_put_contents($file, $twiML->asXML());
require_once 'Twilio.php';
//Initializing Twilio Rest
$sid = "ACcbd06f8e73asdfsdaf1";
$token = "32ccf4bdcasdfsafc";
$client = new Services_Twilio($sid, $token);
$call = $client->account->calls->create("+12asfsaf", "+1ssd8777asfsf7", site_url()."/wp-content/plugins/woocommerce-twilio/order.xml", array());
// echo $call->sid;
} catch (Exception $e){
$error = $e->getMessage();
die($error);
}
}
TL;DR; You need to set the statusCallBack parameter for the options array.
Please see https://stackoverflow.com/a/24482140/1751451
I have this code:
<?php
define('ga_email', 'xxxxxxxxx#xxxxx.com'); // GA Email
define('ga_password', 'xxxxxxxxxxx'); // 2-part authorization password
define('profile_id', 'xxxxxxxxx'); // Analytics profile ID
$gapi_url = 'gapi/gapi.class.php';
require_once $gapi_url;
$ga = new gapi(ga_email,ga_password);
// here goes next code
?>
and it's ok. Gapi will load.
However, if I change ga_password from xxxxxxxxxxx to yyyyyyyyyyy (so the information for logging into GA are incorrect) I get a nasty error, that gapi is not loaded etc.
I need some if condition to implement so it checks if my object $ga was created or not and execte a code only then.
e.g.:
<?php
define('ga_email', 'xxxxxxxxx#xxxxx.com'); // GA Email
define('ga_password', 'yyyyyyyyyyyyyy'); // 2-part authorization password
define('profile_id', 'xxxxxxxxx'); // Analytics profile ID
$gapi_url = 'gapi/gapi.class.php';
require_once $gapi_url;
$ga = new gapi(ga_email,ga_password);
if($ga loaded) {
// SUCCESS
// here goes next code
} else {
// FAILURE
echo "Your connection details are wrong.";
}
?>
So, instead a bad looking PHP error I will get a nicer "Your connection details are wrong."message.
After looking at the source of the class, it appears that the constructor will not throw an exception when the error details are wrong, but only when the credentials are used. Wrapping all your calls to the object in a try...catch block will give you some error handling capabilities:
try {
$ga = new gapi(ga_email,ga_password);
// here goes next code
} catch (Exception $ex) {
// FAILURE
echo "Your connection details are wrong.";
// $ex->getMessage() has a detailed message
}
You also need to ensure you know the correct signature of the constructor method, which appears to be the following:
public function __construct($auth_method)
On your __construct() of gapi check if the username and password is valid. Also create another public function or variable to return whether it is a valid login or not.
given a loop that sends an email to all subscriptions in an array
foreach($subscriptions as $s){
if(!$s->send_email()){
}
}
What would be the cleanest way to trigger a callback if all models have mailed successfully or show an error if one of the models fails to mail. Is it common to save all error messages till the end of the loop and print them as a whole, or break the loop with an error.
I'm using this in combination with a JSON REST API saving a project (/projects/1) which in turn emails all users.
The method I'm using now feels dirty with lot's of nested if else, sending 3 different response on different places
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
if(count($errors) > 0){
//send json api response with error response
} else {
//send json api success response
}
} else {
//send json api response with project error response
}
I was wondering what convention is concerning this
It is a little messy - and it combines multiple concerns within the "save" function - anyone reading the code needs to understand what "save" means, how we loop through the contacts etc.
I'd refactor it as follows:
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
$errors = sendMailToSubscribers($subscriptions);
$response = determineResponse($errors);
// send JSON API response
} else {
//send json api response with project error response
}
function sendMailToSubscribers($subscriptions){
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
return $errors;
}
function determineResponse($errors){
if(count($errors) > 0){
//return json api response with error response
} else {
//return json api success response
}
}
You can use while logic so that failure falls through to the end of the block.
while(1) {
if ($project->save()) {
foreach($subscripts as $s)
if (!$s->send_email())
$errors[] = "failed to send email. Subscription ". $s->id;
} else
$errors[] = 'failed to save the project';
if (empty($errors)) {
//send success here
break;
}
//send your errors here
break;
}