﻿<?PHP
// 本範例使用 cUrl 函式庫, 使用前請先確認 PHP 是否安裝
// 參數使用說明請先參考 API 4.0 技術文件

//簡訊發送
$status = smsSend("testtest","test123","0912345678","簡訊測試");
echo "code: ".$status->code;
echo "text: ".$status->text;
if ($status->code=="00000"){
    echo "msgid: ".$status->msgid;
}

//簡訊查詢發送狀態
$mobile = "0912345678";
$msgid = "222149569";
$status = smsQuery("testtest","test123",$mobile,$msgid);
echo "code: ".$status->code;
echo "text: ".$status->text;
if ($status->code=="00000"){
    echo "statuscode: ".$status->statuscode;
    echo "statustext: ".$status->statustext;
    echo "donetime: ".$status->donetime;
}

// ============ Function ============
function smsSend($username,$password,$mobile,$message){
    $longsms="Y";    
    $message = urlencode($message);
        
    $data = array(
        "username" => $username,
        "password" => $password,
        "mobile" => $mobile,
        "longsms" => $longsms,
        "message" => $message
    );
    
    $ch = curl_init();      
    curl_setopt($ch, CURLOPT_URL, "http://api.twsms.com/json/sms_send.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
    $HTTPResponse = curl_exec($ch); 
    $resultArray = curl_getinfo($ch);
    $http_header_code = $resultArray["http_code"];    
    curl_close ($ch);

    if ($http_header_code=="200"){
        $status = json_decode($HTTPResponse);
    }

    return $status;
}

function smsQuery($username,$password,$mobile,$msgid){
    $data = array(
        "username" => $username,
        "password" => $password,
        "mobile" => $mobile,
        "msgid" => $msgid
    );
        
    $ch = curl_init();      
    curl_setopt($ch, CURLOPT_URL, "http://api.twsms.com/json/sms_query.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
    $HTTPResponse = curl_exec($ch); 
    $resultArray = curl_getinfo($ch);
    $http_header_code = $resultArray["http_code"];    
    curl_close ($ch);

    if ($http_header_code=="200"){
        $status = json_decode($HTTPResponse);
    }
    
    return $status;
}
// ============ Function ============

?>