Trying to send JSON data from my IONIC app to the Twilio PHP API located on my server.
IONIC APP:
I want to send an SMS to whatever mobile number is entered in the form's input (mobile) when the submit button(sendSMS) is clicked:
sendSMS() {
this.submitAttempt = true;
if(this.formGroup.valid){
var link = 'https://mywebsite.com/send-sms.php';
var myData = JSON.stringify({mobile: this.formGroup.controls[ 'mobile' ].value});
this.http.post(link, myData)
.subscribe(data => {
this.data.response = data["_body"];
});
}
PHP handling twilio request:
I don't know what I've missed or done wrong in the code below...I want to send an SMS to the JSON data (mobile input value) received from the IONIC app:
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
$postdata = file_get_contents("php://input");
$account_sid = "mysid";
$auth_token = "mytoken";
$twilio_phone_number = "mymobile";
$request = json_decode($postdata);
$mobile = $request->mobile;
$client = new Client($account_sid, $auth_token);
$client->messages->create(
$mobile,
array(
"from" => $twilio_phone_number,
"body" => "hello"
)
);
Turned out it was a HTTP issue. For anyone else who is trying to use Ionic with a Twilio PHP script on their server:
require_once 'vendor/twilio/sdk/Twilio/autoload.php';
use Twilio\Rest\Client;
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}$postdata = file_get_contents("php://input");if (isset($postdata)) {
$request = json_decode($postdata);
$userMobile = $request->mobile;
if ($userMobile != "") {
echo "Server returns: " . $userMobile;
$account_sid = 'your-twilio-account-sid';
$auth_token = 'your-twilio-authtoken';
$client = new Client($account_sid, $auth_token);
$client->messages->create(
$userMobile,
array(
'From' => "YOUR TWILIO NUMBER",
'Body' => "MESSAGE YOU WANT TO SEND",
)
);
echo "Sent message!";
} else {
echo "Could not send SMS";
} }
Related
If I call the script on browser it does send email to my domain email. Anyway I'm trying to send some contact email from angular 7 apps. I did use HttpClient post and try to send the data as JSON. (Apache server PHP -v 5.6)
I have tried to send the data with URL like mail.php?param1="info#test.test"¶m2="Test email". I did not have any luck. I tried file_get_contents("php://input"); no luck either.
<?php
echo("called");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
// Sanitize.
// $title = $_GET['title'];;
// $message = $_GET['message'];;
// $name = $_GET['name'];;
// $from = $_GET['from'];;
$title = $request->title;
$message = $request->message;
$name = $request->name;
$from = $request->from;
$to = "info#test.com";
// Sending email
if(mail($to, $title, $message, $name)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Here is my Angular Service
export class PollServiceService {
PHP_API_SERVER: string = "/api";
constructor(private http: HttpClient) {
}
public SendEmail(e: any): Observable<any>{
var tmp1 = "/?title=" + e.title + "&message=" +e.message + "&name=" +e.name + "&from=" + e.from ;
return this.http.post<any>(`${this.PHP_API_SERVER}/mail.php`, e);
}
}
I do call the SendEmail(e: any) method on the form. Anyway it does not seem to do to anything. I'm suspect that the php file does not get called at all from the script. Thanks in advance guys.
Your SendEmail function returns an Observable.
You have to subsribe to this Observable in order to make the call happen.
So you should do something like that in a function in your component:
this.pollServiceService.SendEmail(e).subscribe(res => {
// here you can do whatever you want with the result of the call
});
this function should then be called from your form.
I am using localhost server with apache and mysql on xampp. I am implementing a login functionality for which php code is present in my api. When i make a POST request with POSTMAN result comes appropriately but when i make a ajax request i am getting 405 method not allowed error.
I think the headers are appropriately set but still i don't know why error is coming. I would highly appreciate if someone can point out why exactly is error coming and provide a solution code if possible.
this is my js code
```var sendRequest = function(formData) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response = JSON.parse(this.responseText);
console.log("request sent succesfully..");
return response;
}
if (this.readyState == 4 && this.status == 401) {
response = false;
return response;
}
};
request.open("POST","../api/objects/user/login.php",true);
request.setRequestHeader("content-type", "application/json");
request.send(formData);
};```
this is my php code.
<?php
// required headers
header("Access-Control-Allow-Origin:
http://http://127.0.0.1:8080/login.html" );
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-
Headers, Authorization, X-Requested-With");
include_once '../../config/database.php';
include_once 'user.php';
//files for json web token
include_once '../../config/core.php';
include_once '../../libs/php-jwt-master/src/BeforeValidException.php';
include_once '../../libs/php-jwt-master/src/ExpiredException.php';
include_once '../../libs/php-jwt-
master/src/SignatureInvalidException.php';
include_once '../../libs/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
$db = new Database();
$conn = $db->getConnection();
$user = new User($conn);
$data = json_decode(file_get_contents("php://input"));
$user->email = $data->email;
$email_exists = $user->emailExists();
if($email_exists && password_verify($data->password, $user->password))
{
$token = array(
"iss" => $iss,
"aud" => $aud,
"iat" => $iat,
"nbf" => $nbf,
"data" => array(
"id" => $user->id,
"firstname" => $user->firstname,
"lastname" => $user->lastname,
"email" => $user->email
)
);
http_response_code(200);
//generate JWT
$jwt = JWT::encode($token, $key);
echo json_encode(
array(
"message" => "Succesful Login",
"jwt" => $jwt
)
);
}
else {
http_response_code(401);
echo json_encode(array("message" => "Login failed"));
}
?>
postman result on sending email and password as json
{
"message": "Succesful Login",
"jwt":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3QiLCJhdWQiOiJodHRwOlwvXC9sb2NhbGhvc3QiLCJpYXQiOjEzNTY5OTk1MjQsIm5iZiI6MTM1NzAwMDAwMCwiZGF0YSI6eyJpZCI6IjIiLCJmaXJzdG5hbWUiOiJwcmFuYXYiLCJsYXN0bmFtZSI6ImFyb3JhIiwiZW1haWwiOiJhcm9yYS5wcmFuYXYuMjAwMEBnbWFpbC5jb20ifX0.npQWi4HP_QlGmmlkaPve3MBdn8u_yD_MxplUSKebNOY"
}
error shown by browser
login.js:25 POST http://127.0.0.1:8080/api/objects/user/login.php 405 (Method Not Allowed)
I'm trying to make a http post request to my Laravel API from Ionic 4.
I've made other Post successfully before with the same API.
But for some reason I can't make this one work.
The method on the Laravel backend receives an ID and then sends a email with a PDF attached.
I've test it with Postman tool and it works fine. But when I test on the Ionic 4 App it doesn't work.
I tried changing the headers with different options without luck.
I have set the CORS on Laravel backend like this:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
On Postman it works as expected:
https://i.imgur.com/sNuJCzK.png
https://i.imgur.com/ZgLJA20.png
This is my Player.service.ts:
pdf(idPlayer): Observable<any> {
let json = {
idplayer : idPlayer
};
let params = "json=" + JSON.stringify(json);
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Authorization' : localStorage.getItem("token"),
'Content-Type' : 'application/x-www-form-urlencoded',
})
};
console.log("PDF PARAMS:");
console.log(params);
return this._http.post('http://127.0.0.1:8000/api/pdf/email', params, httpOptions);
}
This is the function that calls the service on my Tab-Profile.page.ts:
enviarPdf() {
this._playerService.pdf(this.player._id).subscribe(
response => {
console.log("SEND PDF:");
console.log(response);
},
error => {
console.log("error sendPDF:");
console.log(error);
});
}
This is the error on Chrome console:
EDIT:
Here is my php function in PlayerController.php:
public function ToPdf(Request $request) {
// Obtener usuario identificado
$token = $request->header('Authorization');
$jwtAuth = new \JwtAuth();
$checkToken = $jwtAuth->checkToken($token);
$user = $jwtAuth->checkToken($token, true);
$json = $request->input('json', null);
$params_array = json_decode($json, true);
$id_player = $params_array['idplayer'];
$player = Player::find($id_player);
$pdf = PDF::loadView('templatePdf', $player);
$pdf_name = $player->id . '.pdf';
$content = $pdf->output();
\Storage::disk('players')->put('/pdf/' . $pdf_name, $content);
$exists = \Storage::disk('player')->exists('/pdf/' . $pdf_name);
if (!$exists) {
$data = array(
'code' => 400,
'status' => 'error',
'message' => 'Error PDF.',
'pdf' => $pdf_name
);
}
else {
$email_params = array(
'userName' => $user->name,
'playerId' => $player->id,
'playerName' => $player->name,
'playerSurname' => $player->surname,
);
// Mail::to($user->email)->queue(new EmailPdf($email_params));
Mail::to($user->email)->queue(new EmailPdf($email_params));
\Storage::disk('players')->delete('/pdf/' . $pdf_name);
$data = array(
'code' => 200,
'status' => 'success',
'message' => 'Email sended successfully.',
);
}
return response()->json($data, $data['code']);
}
The second parameter for PDF::loadView() must be an array.
Try to change this
$pdf = PDF::loadView('templatePdf', $player);
into
$pdf = PDF::loadView('templatePdf', ['player'=>$player]);
I'm using the google API to access my calendar entries via OAuth.
Unfortunately I'm getting the following error (server is a local raspi):
Failed to load https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=****-****.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fopenhabianpi..%2Fsmarthome%2Fphp%2Fscripts%2Fscript.oauth2callback.php&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&approval_prompt=auto: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://openhabianpi..' is therefore not allowed access. The response had HTTP status code 405.
My scripts:
Ajax Request
var termine = function (){
$.ajax({
type: "POST",
url: "php/ajax/ajax.termine.php",
data: {
action: 'get_termine'
},n
success: function(response) {
console.log(response);
}
});
}
ajax.termine.php
require dirname(dirname(__FILE__)).'/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(dirname(dirname(__FILE__)).'/config/client_secret.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$service = new Google_Service_Calendar($client);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
echo date('c');
}
}
} else {
$redirect_uri = 'http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
script.oauth2callback
<?php
require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile(dirname(dirname(__FILE__)).'/config/client_secret.json');
$client->setRedirectUri('http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://openhabianpi.***.***/smarthome/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I've tried the following, unfortunately without success:
dataType: 'jsonp',
header("Access-Control-Allow-Origin: *");
Setting in .htaccess or apache.conf
Access-Control-Allow-Origin "*"
Thanks in advance for your help!
if (isset($_SERVER['HTTP_ORIGIN'])){
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
{
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST,OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
You can't use AJAX do do an OAuth authentication as the URL returned by $client->createAuthUrl() will show a login page.
You can still stay on the same page by following this steps:
Open ajax.termine.php in a new tab.
window.open('php/ajax/ajax.termine.php', '_blank');
Set the redirect uri to a blank page that only contains Javascript.
Use this javascript to change the parent page URL.
window.top.location.href = 'http://openhabianpi.***.***/smarthome/';
You simply need to visit your google developer account and under API credentials add your web server address or IP address.
Visit console.developers.google.com
Then select your project.
Then select credentials. Then select your API key. Then select Application restrictions then select HTTP referrers address and add your address.
Hope it solves your issue.
The following script is working via ajax (you have to use a service account for this):
<?php
/**
* Session aufbauen und user check
*/
session_start();
require dirname(dirname(__FILE__)).'/vendor/autoload.php'; //Google API via Composer
$json_path = '***PATH to service account credential JSON***';
$client = new Google_Client();
$client->setAuthConfig($json_path);
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setApplicationName("***Your Appname***");
$service = new Google_Service_Calendar($client);
$calendarId = '***Your CAL ID***';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "";
} else {
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
$date = date("d.m.Y", strtotime($start));
$time = date("G:i", strtotime($start));
$today = date("d.m.Y");
if ($date == $today){
$array[] = array(
"datum" => $date,
"time" => $time,
"termin" => $event->summary
);
}
}
}
echo json_encode($array);
I have a message application for ios in which i wish to use twilio sms service. I need to make a webservice for this purpose, but i am getting an error:
Class 'TwilioRestClient' not found
Can anyone help me with it
<?php
include_once "config.php";
require "twilio-php-latest/Services/Twilio.php";
$phoneno = $_REQUEST['phoneno'];
$selectlist = mysql_query("select * from employee where phoneno = '".$phoneno."'");
//set authentication
$AccountSid = '***';
$Authtoken = '***';
//message values
$data = array(
'From' => "***",
'To' => "$phoneno",
'Body' => "Hello, Your guest has arrived at the reception"
);
//new twilio rest client
$client = new Services_Twilio($AccountSid,$AuthToken);
$response = $client -> request("/$ApiVersion/AccountSid/SMS/Messages","POST",$data);
//check response for success or failure
if($response->IsError)
{
while($post = mysql_fetch_assoc($selectlist))
{
$data[] = $post;
}
header('Content-type: application/json');
echo stripslashes(json_encode(array('error reading sms'=>'$response->ErrorMessage')));//echo" error reading sms: ($response->ErrorMessage)";
}
else
{
header('Content-type: application/json');
echo stripslashes(json_encode(array('sent message'=>'ResponseXml->Sid')));//echo "sent message: ($response->ResponseXml->Sid)";
}
?>