【问题标题】:Sending JSON data from IONIC to Twilio PHP API将 JSON 数据从 IONIC 发送到 Twilio PHP API
【发布时间】:2018-09-27 01:23:39
【问题描述】:

尝试将 JSON 数据从我的 IONIC 应用程序发送到位于我的服务器上的 Twilio PHP API。

离子应用: 当单击提交按钮(sendSMS)时,我想向在表单输入(手机)中输入的任何手机号码发送短信:

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 处理 twilio 请求: 我不知道我在下面的代码中遗漏了什么或做错了什么...我想向从 IONIC 应用程序接收到的 JSON 数据(移动输入值)发送短信:

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"
    )
);

【问题讨论】:

  • 我很乐意提供帮助,但目前很难诊断。你遇到了什么错误?您在流程的哪个阶段收到错误?

标签: php json ionic-framework sms twilio


【解决方案1】:

原来这是一个 HTTP 问题。对于其他尝试在其服务器上使用 Ionic 和 Twilio PHP 脚本的人:

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";
}   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多