https://a.storyblok.com/f/270183/26494/04db90ac87/blog_ionic_sms_1200x600.png

IonicでSMSを送信する方法

最終更新日 November 9, 2020

所要時間:1 分

クロスプラットフォームのモバイルアプリケーションを開発し、サードパーティのAPIに接続することは、技術分野で非常に需要の高いスキルです。今日は、Vonage SMS APIに接続してSMSメッセージを送信する、基本的なIonicモバイルアプリケーションの作り方を紹介します!

私たちはまた hapiバックエンドを構築します。

前提条件

始めるには、以下のものが必要だ:

  • Visual Studio Code、WebStorm、Sublime Textのような優れたIDE

  • Node.jsの最新LTSバージョン

Ionicアプリケーションの作成

Ionicは、クロスプラットフォームのモバイルアプリケーションを迅速に構築するための本格的なフレームワークとツール群です。Angular、Vue.js、またはReactを使用できます。ウェブ開発者の夢だ!

Ionicのインストール

コードをいじる前に、Ionic CLIをインストールする必要がある。

コンソールで以下のコマンドを実行する:

npm install -g ionic

作ろう!

Ionicには、素敵な定型アプリを始めるのに役立つテンプレートがいくつか組み込まれています。UIの下部にタブがあるアプリ、サイドメニューがあるアプリ、または空白のキャンバスを生成することができます。今日は空白のテンプレートを使ってみましょう。

前述したように、Ionicでは複数のウェブフレームワークを使ってクロスプラットフォームのモバイルアプリケーションを構築できる。今日はAngularを使います。

コンソールで実行する:

ionic start

プロジェクト名を尋ねられます。好きな名前をつけてください。私のプロジェクト名は mobile.

次に、ウェブフレームワークを選択するプロンプトが表示されます。次の中から Angular.

すると、すべてのアプリケーション・テンプレートがリストアップされ、その中から選択できるようになります。その中から 空白テンプレートを選択します。

Angularの使用状況に関する匿名データのGoogleへの送信をお願いする場合があります。その選択はあなた次第です。

Angular専用パッケージのインストール

すべてのダウンロードとインストールが完了したら、最後のステップに進みます。もう1つ、Angular用のIonic特有のグッズがたくさん入ったパッケージがあります。

まず、プロジェクト用に作成したionicフォルダに移動します。私は以下のコンソールコマンドを使う必要がありました:

cd mobile

追加パッケージをインストールするには、コンソールで以下を実行する:

npm install @ionic/angular@latest --save

走れ!

すべてがうまくいったことを確認するために、コンソールで以下を実行する:

ionic serve

これで、インターネット・ブラウザ上であなたのボイラープレート・アプリケーションが実行されます。空白のアプリケーションが表示されたら、それを閉じることができます。

より高度なシナリオでは、エミュレーターや、PCに接続されたモバイルデバイスでアプリをテストすることもできる。しかし、それはまた別の機会に。

AngularのHttpClientを設定する

Angularには組み込みの HttpClientクラスが用意されています。今日のチュートリアルでは、組み込みの HttpClientを使います。しかし、以下のような他の一般的なHTTPクライアントライブラリを使用することも可能です。 axios.

まず、HTTPリクエストを発行することをAngularに「伝える」必要がある。そのためには HttpClientModuleがその手助けをしてくれる。をインストールするには HttpClientModuleを開く src/app/app.module.ts.

次に、ファイルの先頭に以下のTypeScriptインポートを追加する:

import { HttpClientModule } from '@angular/common/http';

次に @NgModuleデコレータ内に HttpClientModuleを追加します。 importsプロパティを追加します:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [], // ** 👇 right here! **
  imports: [BrowserModule, HttpClientModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

優れたUIを構築する

私たちのボイラープレート・アプリケーションには、すでに以下のページが作成されています。 src/app/home/home.page.html.

開けて、内部を <div id="container">を以下のように交換する:

<ion-grid>
  <ion-row>
    <ion-col class="ion-align-self-center">
      <ion-input placeholder="Enter your SMS message" [(ngmodel)]="text"></ion-input>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col class="ion-align-self-center">
      <ion-input placeholder="Enter the sender phone #" [(ngmodel)]="from" type="tel"></ion-input>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col class="ion-align-self-center">
      <ion-input placeholder="Enter the destination phone #" [(ngmodel)]="to" type="tel"></ion-input>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col class="ion-align-self-center">
      <ion-button expand="full" color="primary" (click)="sendSms()">
        Send It!
        <ion-icon slot="end" name="send-outline"></ion-icon>
      </ion-button>
    </ion-col>
  </ion-row>
</ion-grid>

UIページのコード・ビハインド

次に、UIページをバックエンドに接続する必要があります。ファイルを src/app/home/home.page.ts.

今回も、私が力仕事をしてあげた!ファイルの中身を以下のように置き換えるだけだ:

// import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { AlertController } from '@ionic/angular';
import { Component } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  public text: string;
  public from: string;
  public to: string;

  constructor(private http: HttpClient, private alert: AlertController) { }

  public sendSms() {
    const payload = new HttpParams()
      .set('from', this.from)
      .set('to', this.to)
      .set('text', this.text);

    return this.http.post('http://sms.com:3000/send-sms', payload)
      .pipe(
        catchError((error: HttpErrorResponse) => {
          this.alert.create({ message: 'Oops!'})
            .then((alert) => alert.present());
          return throwError('Oops!');
        }))
      .subscribe(async (resp: any) => {
        const alert = await this.alert.create({ message: resp.message });
        await alert.present();
      });
  }
}

テストしてみよう!

コンソールで ionic serveを実行してアプリケーションを実行し、アプリが実行されていることを確認してください。

Hapiを使ったバックエンド

hapiを使ってバックエンドを作りましょう!

まず、バックエンド・コード用のディレクトリを作成します。 mkdir backend && cd backendを実行して、バックエンド・コード用のディレクトリを作成します。

次に npm install @hapi/hapi @vonage/server-sdkを実行して hapi と Vonage API クライアントをインストールする。

ベーシックHTTPサーバー

ファイルを作成し /backend/index.jsを作成し、そこに以下を記入する:

'use strict';

const Hapi = require('@hapi/hapi');
const Vonage = require('@vonage/server-sdk');
const {
    Console
} = require('console');

const vonage = new Vonage({
    apiKey: /** PUT YOUR KEY HERE! **/
    apiSecret: /** PUT YOUR SECRET HERE! **/
}, {
    debug: true
});

const init = async () => {

    const server = Hapi.server({
        port: 3000,
        host: 'localhost',
        routes: {
            cors: {
                origin: ['*']
            }
        }
    });
    server.route({
        method: 'POST',
        path: '/send-sms',
        options: {
            cors: true,
            handler: async (request, h) => {
                const payload = request.payload;
                const result = await new Promise((resolve, reject) => {
                    vonage.message.sendSms(payload.from, payload.to, payload.text, (error, response) => {
                        if (error) {
                            return reject(error)
                        } else {
                            return resolve(response);
                        }
                    });
                });

                console.log(JSON.stringify(result));

                if (result.messages[0].status === '0') {
                    return { message: 'It Worked!' };
                } else {
                    return { message: result.messages[0]['error-text'] };
                }
            }
        }
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

APIキーとシークレットを置き換えてください!

恐るべきCORS

にあるバックエンドAPIにIonicアプリケーションを接続する場合、CORSに関連する問題が発生します。 localhostにあるバックエンドAPIにIonicアプリケーションを接続する場合、CORSに関連するいくつかの問題が発生します。

開発中にこれを修正するには、管理者としてhostsファイルを開く必要があります。Windows 10の場合、hostsファイルは以下の場所にあります。 C:\Windows\System32\drivers\etc\hosts.Linuxマシンでは通常 /etc/hosts.

次の行を追加する:

127.0.0.1 sms.com

に移動するたびに、ローカルマシンはそのHTTPリクエストを sms.comにナビゲートすると、ローカルマシンはそのHTTPリクエストを localhost.これは、ウェブ・ブラウザが本物のドメインにアクセスしていると思い込ませているだけなのだ。

走りましょう!

よし!2つのコンソールを開く。

ひとつは /mobileを実行し ionic serve.

もう一方では /backendに移動し node index.js.

Vonageダッシュボードで提供される Vonageダッシュボードで提供されたテスト番号を使ってSMSメッセージを送信してください!

シェア:

https://a.storyblok.com/f/270183/384x384/624c6e3593/james-hickey.png
James Hickey

James is a Microsoft MVP with a background in fintech & insurance industries building web and mobile applications. He's the author of Refactoring TypeScript and the creator of some open-source tools for .NET called Coravel. He lives in eastern Canada and is a 10-minute drive from the highest tides in the world!