I am new to the Twilio PHP API and am finding it difficult using the sample code and even finding the correct documentation on the Twilio site to help me implement SMS messaging into our web app.
After much trial and error, and reading through some postings on this site, I have gotten far enough to figure out how to send a simple SMS message and even use a try/catch structure to deal with bad recipient phone numbers.
What I cannot for the life of me figure out is how to catch authentication errors with a client's SID and AUTH token. I'd like to catch authentication errors for a client's credentials before I try even sending messages for them. Some clients may blast a message to 200 customers so I don't want to spin my wheels if their authenticaiton fails. Heres what I have been trying:
require_once K_DOCROOT.'/includes/twilio-php-main/src/Twilio/autoload.php';
// use Twilio\Rest\Client;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = "ACf6eXXXGGGDDDDDDDDDDDDDDDDDDDDDDD"; // intentionally incorrect
$token = "164d3a88f753e553691960fb4d405f82";
$dest = "+15106443333"; // recipient number
try {
$twilio = new Twilio\Rest\Client($sid, $token); // Had to change this to make it work without the USE above
// $message = $twilio->messages->create($dest, // to
// [
// "body" => "Testing 123",
// "from" => "+19998887777"
// ]
// );
//
// echo "Results: ".$message->sid;
}
catch (Exception $e) {
echo $e->getCode()." : ".$e->getMessage();
}
When I run this without the $twilio->messages->create() code, I get nothing... no errors, no responses whatsoever. If I uncomment the create() section where I try and send a message, I get the following:
20003 : [HTTP 401] Unable to create record: Authentication Error - invalid username
Which makes sense. But it is forcing me to catch the authentication error when sending a message and not before.
Maybe I am missing something, but is there some way to check for authentication errors, or get back some sort of status code letting me know a client's authentication was successful or not?
Also, if you have a link to the documentation that covers error handling for Client() calls, I would greatly appreciate it.
Related
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 have set some mail quota's on email addresses that I manage through Plesk.
However, users are complaining that they are not being informed when their inbox is full or nearly full.
So my idea was to send an email to them when their inbox is about 90% full, so I was wondering if I can retrieve mail account information using PHP?
If not, is there another way of doing this? (I'm not too familiar with console commands)
In this answer I skip the Plesk API altogether, and I assume you either store the properties of the mailboxes in a database, hardcode it, or actually use the Plesk API to retrieve it.
Here is how I retrieve the space used by a mailbox:
function getSpaceUsedByMailBox($username,$password)
{
// open mailbox
$mailBox = imap_open('{localhost:110/pop3/novalidate-cert}INBOX',$username,$password);
// test if successful
$errors = imap_errors();
if ($errors === FALSE)
{
// get info
$info = imap_mailboxmsginfo($mailBox);
// give feedback
echo "Mailbox of $username contains ".$info->Nmsgs.
' messages and is '.$info->Size.' bytes big.';
// flush notices
imap_errors();
imap_alerts();
// close mailbox
imap_close($mailBox);
// return info
return $info;
}
// change this to proper error handling
echo 'ERROR: '.print_r($errors);
// return nothing
return NULL;
}
This is just to give you an idea. You have to adapt it to your coding style.
I am working on an eCommerce site that sends a number of emails to the customer when they complete their order using G Suite SMTP relay service. But a large number of these emails are failing. There does not seems to be any pattern to it either - sometimes all emails will send, some times just one or two, and sometimes none.
I am getting the following error: 421, "4.7.0", Try again later, closing connection.
Looking here: https://support.google.com/a/answer/3726730?hl=en doesn't really help me debug this or figure out why some emails fail.
I am using the phpmailer class (https://sourceforge.net/projects/phpmailer/)
The issue seems to occur when the first handshake fails:
function Hello($host="") {
$this->error = null; # so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Hello() without being connected");
return false;
}
# if a hostname for the HELO was not specified determine
# a suitable one to send
if(empty($host)) {
# we need to determine some sort of appopiate default
# to send to the server
$host = "localhost";
}
// Send extended hello first (RFC 2821)
//If this fails then the second attempt will always fail
if(!$this->SendHello("EHLO", $host))
{
//when this fails it generates the try again later error
if(!$this->SendHello("HELO", $host))
return false;
}
return true;
}
So what is the best approach for debugging this?
The error message is pretty explicit. You call a 3rd party web service, which returns an error code which says the server you are calling is at capacity, try later. Is this a free service which allows you to upgrade to a paid plan? Usually whee you see his kind of thing.
I'm using Excel VBA to get a user's oAuth2 token for the mail.google.com scope for a native application. It works fine so I have the the user's Access Token (it refreshes if it expires) and I have the user's email address. I was using Zend SMTP to send the emails but found out there are limits to bulk sending emails this way (currently my account is locked out due to going over quota while trying to figure this out over the weekend). My client may send 2,000 emails at once and locking themselves out of their Gmail account for 24 hours is unacceptable. I think using the Gmail REST API will work, as it has higher quotas, but not finding any detailed PHP examples of how to create and send an HTML email via an HTTP request.
I know I have to create the MIME email and think I can figure that out (using this thread stackoverflow.com/questions/24940984/send-email-using-gmail-api-and-google-api-php-client) or from the Zend emails I was successfully creating. My question is what PHP code do I use to create and send the email?
The Google Dev examples all reference /userId/ (from developers.google.com/gmail/api/v1/reference/) but not sure where to get that if I just have the users token and their email address.
I assume it's something like this:
<?php
require 'GoogleAPI/src/Google/autoload.php';
extract($_POST); // use to get my client token, client's email address, the email to, cc, bcc, subject, body, etc.
//<Build the email $mime message here>
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
?>
I don't know where to put the user's token. I know 'me' is the person that is authenticated.
I'm open to using an HTTP request as well, something like https://mywebsite.com/sendgmail.php?token=[UsersToken]&UserEmail=joe#test.com&ToEmail=toperson#xyz.com&Subject=HI&Body=Thanks for your help instead of the post method.
Just not sure how to implement that either.
I'm self taught PHP and VBA and new to the google api world so please forgive me if this is easy. I'm also looking into boxspring but trying to use the native APIs and PHP first.
EDIT:
So I've tried this using the examples but getting an error that my token is not in proper JSON format. I just want to send the token as a string. If I can't is there a way to make the string into JSON so oauth2 will accept it?:
<?php
require 'GoogleAPI/src/Google/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setAccessToken('ya29.hwFcwk2M73vaPwNObeuwizHGjXT2y6UsAFEcDIvRAoWTM28gu2pJeK4GiMySkfAllTOQvXVMYfffff');
// Get the API client and construct the service object.
//$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
?>
Error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Could not json decode the token' in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php:179
Stack trace: #0
/home/[my domain]/public/GoogleAPI/src/Google/Client.php(215):
Google_Auth_OAuth2->setAccessToken('ya29.hwFcwk2M73...') #1
/home/[my domain]/public/labels.php(17):
Google_Client->setAccessToken('ya29.hwFcwk2M73...') #2 {main} thrown
in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php
on line 179
I'm sure I'm making this more difficult than it should be. I'm using the PHP example of showing a users labels, even though my final goal is to send emails.
I make use of a great class made by Jaisen: http://github.com/jmathai/twitter-async/tree/master. Recently twitter has been up and down and I am sure it will continue to be the same in the future so I am trying to cut down on my dependency on twitter being actually working.
The following is what I have in my header.php and it is right at the top and it generates the login URL for each user. If twitter is down, my site hangs for as long as it needs to and it throws an exception. So I have to catch these expceptions which I have sort of done.
I now want to just cancel the request to the API after a few seconds and just load the page and keep trying behind the scenes. How can I best do this?
<?php include './twitter/EpiCurl.php'; include './twitter/EpiOAuth.php'; include './twitter/EpiTwitter.php';
$consumer_key = 'mykey';
$consumer_secret = 'mysecret';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
try{
$twiturl = $twitterObj->getAuthenticateUrl();
$url = "window.open('".$twiturl."','Login', 'left=20,top=20,width=500,height=500,toolbar=0,resizable=1'); startLoad();";
}catch(EpiOAuthBadRequestException $e){
// bad request exception do something
$statusMessage = 'Oops an error has occurred: ' . $e->getMessage();
}catch(EpiOAuthUnauthorizedException $e){
// bad authorization..probably bad tokens, do something different
$statusMessage = 'Oops an error has occurred: ' . $e->getMessage();
}catch(EpiOAuthException $e){
// uh oh, unknown oauth exception
$statusMessage = 'Oops, an unknown authorisation error has occurred! The mojo team have been notified! Please try again.';
}
if(isset($statusMessage)){
}
?>
Any improvement of the above code will also be appreciated.
Thanks all
The library supports a value to be passed into the curl timeout.
$twitterObj->setTimeout($secs_request_timeout);
I just added support for passing in a connection timeout as well. Unable to run unit tests because I'm being rate limited. Will commit this once I can verify that it works.
$twitterObj->setTimeout($secs_request_timeout, $secs_connection_timeout);
Use curl_setopt(CURLOPT_CONNECTTIMEOUT, 1 /* 1 second timeout */); to cause CURL to give up if a connection isn't established in 1 second. I use this when connecting to the facebook API, 'cause they've been pretty unreliable in the past as well.