LoginSignup
5
4

More than 3 years have passed since last update.

Delphi10 でTwilio apiを叩いてSMSメッセージを送る

Last updated at Posted at 2020-05-03

はじめに

Delphi10 お試しシリーズ第4弾
今回は Twilio のapiを使ってSMSメッセージを送ってみました。
全く同じソースでWindows、Android共に動作します。(FireMonkey万歳!)

Twilioアカウント取得

事前にTwilioのアカウントを取得しておきます。
方法はググってください。無料トライアルのアカウントがありましたので
そちらを使っています。
アカウントをとると約1600円($15?)のトライアルバランスが付加されました。
電話番号をとると107円($1?)  SMSを送ると1通につき9円掛かるようです。
SMS送信に必要なのはAccount SID,AUTH TOKEN,電話番号の3つです。

画面作成

以下の画面イメージの様に必要なコンポーネントを配置します。

image.png

ソースリスト

unit rest1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, REST.Types,
  FMX.Controls.Presentation, FMX.StdCtrls, Data.Bind.Components,
  Data.Bind.ObjectScope, REST.Client, REST.Authenticator.Basic, FMX.ScrollBox,
  FMX.Memo, FMX.Edit;

type
  TForm1 = class(TForm)
    RESTClient1: TRESTClient;
    btn_send: TButton;
    HTTPBasicAuthenticator1: THTTPBasicAuthenticator;
    RESTRequest1: TRESTRequest;
    RESTResponse1: TRESTResponse;
    Memo1: TMemo;
    ed_message: TEdit;
    ed_account: TEdit;
    ed_token: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    ed_to: TEdit;
    Label5: TLabel;
    ed_from: TEdit;
    procedure btn_sendClick(Sender: TObject);
  private
    { private 宣言 }
  public
    { public 宣言 }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.btn_sendClick(Sender: TObject);
begin
  HTTPBasicAuthenticator1.Username := ed_account.Text;
  HTTPBasicAuthenticator1.Password := ed_token.Text;

  RESTRequest1.Method := rmPost;
  RESTRequest1.Client := RESTClient1;
  RESTRequest1.Response := RESTResponse1;

  RESTClient1.BaseURL :=
      format('https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json',[ed_account.text]);
  RESTClient1.Authenticator := HTTPBasicAuthenticator1;

  with RESTClient1.Params do
  begin
    Clear;
    AddItem('To',ed_to.Text);
    AddItem('From',ed_from.Text);
    AddItem('Body',ed_message.Text);
  end;

  RESTRequest1.Execute;
  memo1.lines.text := RESTResponse1.Content;
end;
end.

実行

入力ボックスにパラメータを入れてSend SMSボタンを押すと、スマホにSMSメッセージが届きました。
めでたし めでたし。

画面下のメモコンポーネントにレスポンス内容を表示しますので、上手くいかない場合は
エラー内容を頑張って読み解いてください。
To:には携帯番号の頭に+81(日本の国番号)をつけています。

5
4
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
5
4