LoginSignup
6
7

More than 5 years have passed since last update.

Twilioで電話するメモ

Posted at

「ある電話番号へ自動的に電話をし、相手が出たら、メッセージを流し、営業マンの携帯電話に転送してほしい」的な話があったので調べたら、twilio http://twilio.kddi-web.com/ を使った発着信の制御がすごく簡単だった。

以下はテストアカウントで少し試したもの。
(新規登録時、お試しでしばらく無料で利用できる)
テストで作成したので、一部はサンプルのまま。

twilio.php
<?php
// PHPのSDKを利用する 
require('twilio-php/Services/Twilio.php'); 

// 1. 発信。引数 'call'をつけて、PHPスクリプトを実行する。
if (isset($argv)) {
    if (in_array('call', $argv)) {
        phone('+813xxxxxxxx');
        echo "phone¥n";
        exit();
    }
}

// 2. 発信が受け取られた場合、登録済みのURL(?hello=1)が呼び出される 
if (isset($_GET['hello'])){
    header("content-type: text/xml");
    // TWIMLを出力
    echo <<<_EOD_
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>This is Seraph Test.</Say>
  <Play>http://example.com/monkey.mp3</Play>
  <Gather numDigits="1" action="twilio.php" method="POST">
    <Say>To speak to a real monkey, press 5.  Press any other key to start over.</Say>
  </Gather>
</Response>
_EOD_;

    exit();
}

// 3. キーが押されると呼び出される
if (isset($_POST['Digits'])) {
    // 押されたキーが'5'の場合
    if ($_POST['Digits'] == '5') {
        // '+813xxxxxxxx'へ電話を転送する
        header("content-type: text/xml");
        // TWIMLを出力
        echo <<<_EOD_
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>+813xxxxxxxx</Dial>
    <Say>The call failed or the remote party hung up. Goodbye.</Say>
</Response>
_EOD_;

    } else {
        // 処理2を再び行う
        header('Location: ' . $url . 'twilio.php?hello=1');
    }
    exit();
}


echo "end\n";
exit();

/**
 * 発信用関数
 * @param string $to 発信先電話番号
 */
function phone($to) {

    $account_sid = "0123456789012345678901234567890123";
    $auth_token = "0123456789012345678901234567890123";

    // 登録済みのApplicationSid
    $application_sid = "0123456789012345678901234567890123";

    // 発信元電話番号
    $from = '+813xxxxxxxx';

    $client = new Services_Twilio($account_sid, $auth_token); 

    // パラメータは適時変更する
    $client->account->calls->create($from, $to, $application_sid, array( 
        'Method' => 'GET',  
        'FallbackMethod' => 'GET',  
        'StatusCallbackMethod' => 'GET',    
        'Record' => 'true', 
    ));
}
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7