WhatsApp chatbot with Twilio using Php - php

I am trying to create a chatbot using laravel php and Twilio Api. I am still in sandbox. This the code i currently have
public function commandHandler(Request $request){
$from = $request->input('From'); // phone number where the message is coming from
$body = $request->input('Body');// what user wrote
$client = new \GuzzleHttp\Client();
try {
$response = $client->request('GET', "https://api.github.com/users/$body"); //test if network is working
if ($response->getStatusCode() == 200) {
$message = "Welcome to System. \n";
$message .= "To Log In, Enter Email Address";
$this->sendWhatsAppMessage($message, $from);
} else {
$this->sendWhatsAppMessage("Error", $from);
}
} catch (RequestException $th) {
$response = json_decode($th->getResponse()->getBody());
$this->sendWhatsAppMessage($response->message, $from);
}
return;
}
I can get what user has typed from the variable $body and send user back a message through the function
$this->sendWhatsAppMessage($response->message, $from);
but the problem is when i want the user to enter password, it goes to the same url and does the same functions of which i would like for it to do different functions. Twilio only accepts one call-back url which i have to use that one function only. How do i use different functions for different messages sent to the user
this is what is in my api.php
Route::post('/chat', 'App\Http\Controllers\ChatBotController#listenToReplies');
and that is the url in the callback of the Twilio dashboard

Related

ios notifications not receiving in Kreait\Firebase

All the things working perfect on android but ios not receiving any message from php backend api.
CASE 1 : successfully receiving PN on mobile app when testing from here https://www.pushtry.com/ when app in background mode.
CASE 2: Below php script not sending PN not even in background mode app.
Here is php api code script.
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
public function send_push($target_user_id)
{
$fcm_token = get_user_meta($target_user_id, 'fcm_token', true);
if (!empty($fcm_token)) {
$title = "Your Invitation Was Accepted";
$body = 'Click here to start game';
try {
$message = CloudMessage::withTarget('token', $fcm_token)
->withNotification(Notification::create($title, $body))
->withData([
'notification_type' => 'invitation_accepted',
'title' => $title,
'body' => "Your partner's accepted your invitation",
]);
$this->messaging->send($message);
} catch (\Throwable $e) {
// for PHP 7.x
$this->on_error($e);
} catch (\Exception $e) {
// for PHP 5.x
$this->on_error($e);
}
}
}
Can someone please help me to guide for ios :)

Why my Stripe Webhook function is not working(test mode)?

I has create a webhook php to trigger the paymentintent event status. I had successfully tigger it but the function of detected event is no working which i just want to redirect to another page if successful or not. I try to echo text, it also not showing. I can see the response body(show the text that i want to echo" in the dashboard of Stripe. Did i misunderstanding the concept of it ? This is my code:
<?php
/*
Template Name: webhook
*/
include_once(get_template_directory_uri().'/customFile/stripe-php-7.71.0/init.php');
\Stripe\Stripe::setApiKey('xxx'); // this is true, i just replace with xxx
$payload = #file_get_contents('php://input');
$event = null;
$paymentstatus = "Payment Failed";
try {
$event = \Stripe\Event::constructFrom(
json_decode($payload, true)
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
// Handle the event
switch ($event->type) {
case 'payment_intent.succeeded':
$paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
//handlePaymentIntentSucceeded($paymentIntent);
echo"Success";
echo "<script>location.href='http://localhost/wordpress/';</script>";
break;
case 'payment_intent.payment_failed':
$paymentMethod = $event->data->object; // contains a \Stripe\PaymentMethod
//handlePaymentMethodAttached($paymentMethod);
echo "<script>location.href='http://localhost/wordpress/shop/';</script>";
break;
}
http_response_code(200);
Webhooks are requests that come from Stripe to your web server. There's no user attached to these events so trying to redirect after you receive a webhook event makes no sense. All that's happening is you're sending a <script> string back to Stripe, who promptly ignores it because all they are about is the response status code.
If you want to redirect your user after they've made a successful payment, you should either that on the client after they've confirmed the PaymentIntent or in your success_url if you're using Checkout.

Twilio doesn't call my TwiML instruction url

I'm using Twilio to send a verification code through voice call. I've used this tutorial to write the code:
https://www.twilio.com/blog/implement-account-verification-login-by-phone-laravel-php
So, that's basically the code. My phone rings and I get the "You have a test account, press any key to run your code" message, but when I press a key, it hangs up on me and my code is never called.
public function sendVerificationCodeThroughCall($mobile)
{
$code = $this->createMobileCode($mobile);
$client = new Client(config('services.twilio.sid'), config('services.twilio.auth_token'));
$client->calls->create(
$mobile,
config('services.twilio.phone_number'),
["url" => route('voice-code.build', $code)]
);
}
public function buildVoiceCode($code)
{
Log::debug('Twilio called to say: ' . $code);
$code = $this->splitCode($code);
$response = new VoiceResponse();
$response->say("Salaam. This is your verification code: {$code}. I repeat, {$code}.");
echo $response;
}
protected function splitCode($code)
{
return implode('.', str_split($code));
}

How to run a function upon successful execution of another function

I have 2 functions that uses Twilio to send media files and text messages respectively. Most times, I want to send photo then a text message. However, when I call both functions, the text message sends before the photo. How do I ensure that the photo sends first before the text.
//sends photo
public static function sendMediaMessage($phone, $mediaUrl, $msg = null){
try{
$client = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));
$send = $client->messages->create(
"whatsapp:".$phone,
array(
'from' => "whatsapp:".env('TWILIO_NUMBER'),
'body' => $msg,
'mediaUrl' => [$mediaUrl],
)
);
}catch (\Exception $exception){
}
}
//send text messages
public static function sendWhatsAppMessage($phone, $message){
try{
$client = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));
$send = $client->messages->create(
"whatsapp:".$phone, // Text this number
array(
'from' => "whatsapp:".env('TWILIO_NUMBER'),
'body' => $message
)
);
}catch (\Exception $exception){
}
}
Makes call
myClass::sendMediaMessage();
myClass::sendWhatsAppMessage();
Twillio documentation suggests you can supply a callback url using the statusCallback field.
If specified, we POST these message status changes to the URL: queued, failed, sent, delivered, or undelivered.
You could configure a route for it and then send the second message.
Alternatively you could look into the message feedback system Twillio has in place.
To track message feedback, you must set ProvideFeedback=true when you first create the Message. This will create a Message Feedback instance with an Outcome of unconfirmed.
I'm not sure which of the above should be used, that's up to you.

Handle 500 internal server error while sending SMS using twilio in PHP

I am using Twilio sdk to send SMS in my PHP based application,I have an array of phone numbers and sending an SMS to each number in this array in a loop.....the problem is while the loop is running if an invalid number comes twilio API returns 500 internal server error and it stops the loop without trying sending sms for rest of the numbers in the array.
This is the code I am using for sending sms :
public function sendSmsAction($userphones)
{
foreach($userphones as $user_phone)
{
$message = 'Thanks for coming';
$this->twiliosms($user_phone,$message);
}
}
private function twiliosms($phone_num,$message)
{
require Mage::getBaseDir()."/twilio-php-master/Services/Twilio.php";
$AccountSid = "XXXXXXX";
$AuthToken = "XXXXXXX";
$client = new Services_Twilio($AccountSid, $AuthToken);
try {
$message = $client->account->messages->create(array(
"From" => "+1XXXXXXXXXX",
"To" => $phone_num,
"Body" => $message,
));
} catch (Services_Twilio_RestException $e) {
echo $e->getMessage();
}
}
And this is the error I am getting :
Status: 500 Internal Server Error
The 'To' number +1XXXXXXXXXX is not a valid phone number or shortcode.
please help me out in handling this error.
Thanks in advance.
Finally, I got my solution....by just adding another catch() made it working fine...
catch(Exception $e)
{
}

Categories