Twilio ignoring errors in PHP library - php

I have a problem. I have set up the Twilio helper library in PHP to send SMS and everything works fine. But I need to do something and I cant figure out how to do it.
Here is the working code:
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
if(!$sms){ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
} else {
$count=0;
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
Everything works fine. The problem is when an error happens because of a broken phone, the loop which goes through the array breaks and sending stops. I need to keep sending, how could I do this? This is controller and requests is sent from ajax call, thats why there are echo statements!

When exception throws, the foreach loop breaks and execution comes to catch
So make your code as
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
try
{
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
An additional try catch block within foreach loop

Here's the same code but a bit trimmed... This worked for me!
<?PHP
require "Services/Twilio.php";
// Set our AccountSid and AuthToken from twilio.com/user/account
$AccountSid = "{ACCOUNTSID}";
$AuthToken = "{AUTHTOKEN}";
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);
/* Your Twilio Number or Outgoing Caller ID */
$from = '2126404004';
$people = array("212-716-1130");
$body = "Enter your text message here";
$errorIds = array(); //user ids array which had broken phones
foreach ($people as $to) {
try
{
$client->account->sms_messages->create($from, $to, $body);
echo "Sent message to: $to \n <br>";
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $to);
}
}
print_r($errorIds);
?>

Related

Query executed without errors but no data in database

After executing the SQL file below to create the appropriate tables(which gets executed correctly without errors),
<?php
try {
require_once 'dbcon.php';
$sql_file = 'mysql.sql';
$contents = file_get_contents($sql_file);
$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/',
'/\s*--.*\n/',
'/\s*#.*\n/',
);
$contents = preg_replace($comment_patterns, "\n", $contents);
$statements = explode(";\n", $contents);
$statements = preg_replace("/\s/", ' ', $statements);
foreach ($statements as $query) {
if(trim($query) != '') {
$db->query($query);
if ($db->errno) {
throw new Exception("Fail to load data in database (".$db->errno.")");
}
}
}
Running the following query right after the foreach gets executed successfully without errors and success message gets printed. However , no data gets inserted into the database.
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
$cstmt->execute();
if($cstmt->affected_rows === 1){
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}
?>
I have printed out $cstmt->error and $cstmt->errno and they all return 0 . which seems fine but don't why the data doesn't get inserted into the fields. Anything am missing or doing wrong?
Try this:
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
**if($cstmt->execute()){**
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}

Try Catch method in destroy function laravel

Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
the try/catch method is not working compared to my previous store function that is working
Read up further on findOrFail. You can catch the exception it throws when it fails to find.
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);

My Stripe payment is working perfect. But now i want to catch from Database

I am using Stripe Payment. I have integrated the Stripe checkout system in my Php website.
With Static prices it works good. But not I want to get Prices from My Database. And it shows on screen that it is charged. But in my strip account it is not sending money..
$charge = Stripe_Charge::create(array(
"amount" => 999999, // I want here $price from my database.
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
When i Add $price instead of static price 99999 it not sends money to my stripe payments. But when i add 99999 again , it start working. My Database is Okay All veriables and database connections are okay. Issue is only here.. How i can get it fixed..
If you want my full code..
include 'header.php'; //Connection File is in header.php
error_reporting(0);
try {
require_once('Stripe/lib/Stripe.php');
Stripe::setApiKey("sk_test_GkvxX3TWD6juGRLhZwP2LQ1x");
$req_id = $_REQUEST['order_id'];
$get_req = "SELECT * FROM `requests` WHERE `req_id` = '$req_id'";
$result = mysqli_query($dbc, $get_req);
while($row = mysqli_fetch_array($result)){
$req_id = $row['req_id'];
$request_title = $row['request_title'];
$username = $row['username'];
$user_id = $row['user_id'];
$price = $row['price'];
$request_time = $row['request_time'];
$req_date = $row['req_date'];
$category = $row['category'];
$sub_category = $row['sub_category'];
$from_address = $row['from_address'];
$to_address = $row['to_address'];
$from_state = $row['from_state'];
$to_state = $row['to_state'];
$from_city = $row['from_city'];
$to_city = $row['to_city'];
$req_desc = $row['req_desc'];
$status = $row['req_status'];
$paid = $row['paid'];
}
$charge = Stripe_Charge::create(array(
"amount" => 999999,
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
$status = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
echo 'Payment Done ';
$status = 1;
//print_r($token);
} else {
$errors['token'] = 'The order cannot be processed. You have not been charged.
Please confirm that you have JavaScript enabled and try again.';
echo "payment not successfully done.Please try again";
$status = 0;
}
} // End of form submission conditional.
}
catch(Stripe_CardError $e) {
}
//catch the errors in any way you like
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
if($status2 = 1){
$query = "UPDATE `requests` SET `req_status`='1', `paid`='1' WHERE `req_id`='$req_id'";
$result = mysqli_query($dbc,$query);
}else{
}
I have not seen in your code, what the output of $price is. So, while I do
not assume that $price, drawn from your database, is incorrectly prepared,
it is as mentioned in the Stripe documentation, necessary to express the
price in cents. Such that if you place this code
$findme = ".";
$pos = strpos($price, $findme);
$PosPlus = $pos+1;
$Part1=substr($price, 0, $pos);
$Part2=substr($price, $PosPlus);
$price = ($Part1.$Part2);
above the line you have,
$charge = Stripe_Charge::create(array( //.....
your charge should succeed.

my $_SESSION["message"] echoing everywhere even there is if

I have one problem.I wanted to echo my message ("subject created", "subject creation failed" depending on whether my subject is created or not). The problem is the message is on every page even though setting the $_SESSION["message"] is under if condition . I really don't know where is the problem. I lost probably 2 hours on this...
All includes and requires are included...
This is on my proceeding page:
if(isset($_POST["submit"])) {
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "INSERT INTO subjects(";
$query .= " menu_name, position, visible ";
$query .= ") VALUES ('{$menu_name}', '{$position}', '{$visible}')";
$result = mysqli_query($connection,$query);
if($result) {
//success //
$_SESSION["message"] = "Subject created";
redirect_to("manage_content.php");
} else {
$_SESSION["message"] = "Subject creation failed";
redirect_to("create_new_content.php");
}
} else {
redirect_to("create_new_content.php");
}
my message function is:
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
return $output;
}
}
and after all Im echoing on my manage_content.php and create_new_content.php
<?php echo message(); ?>
You should clear the session when its not needed any more.
E.g.
unset($_SESSION['message']);
Try to clear your $_SESSION message and check if is not empty
function message() {
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])){
$output = $_SESSION["message"];
$_SESSION["message"] = '';
return $output;
}
}
if you show your message only one time, you need to clear the $_SESSION["message"] before return
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
// clear the session message
$_SESSION["message"] = null;
// remove message index from $_SESSION
unset($_SESSION["message"]);
return $output;
}
}

How to identify sql query is executed or not?

$sql='SELECT sender
FROM messages
WHERE message_id = :message_id';
$sender_result = $db->query($sql, array(':message_id'=>$message_id));
$sender = $sender_result->fetch();
I use this to execute above sql. How can I use $sender in the If.
Try using TRY-CATCH as:
try {
$sql='SELECT sender
FROM messages
WHERE message_id = :message_id';
$sender_result = $db->query($sql, array(':message_id'=>$message_id));
$sender = $sender_result->fetch();
} catch(PDOException $ex) {
// handle exception by using your own logic
echo "An Error occured!"; //a custom error message
your_logging_function($ex->getMessage());
}
This is the simplest way you could test
$query = $DB->query(".....");
if($query) // will return true if succefull else it will return false
{
// code here
}
if(isset($sender[0]))){
return TRUE;
}
else {
return FALSE;
}

Categories