3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel AmazonSNSでSMS送信

Last updated at Posted at 2022-03-10

こちらの記事を参考にしています。AWSの設定は省きます。
https://codeeee.net/posts/laravel-amazon-sns-send-sms

AWSのパッケージをcomposerでインストール。

COMPOSER_MEMORY_LIMIT=-1 composer require aws/aws-sdk-php-laravel

プロバイダ追加

config/app.php
'providers' => [
  //...
  Aws\Laravel\AwsServiceProvider::class,
],

コマンドで設定ファイルを作成

php artisan vendor:publish  --provider="Aws\Laravel\AwsServiceProvider"

以下にファイル設定が作成される

config/aws.php
 'credentials' => [
        'key'    => env('AWS_ACCESS_KEY_ID', ''),
        'secret' => env('AWS_SECRET_ACCESS_KEY', ''),
    ],
    'region' => env('AWS_REGION', 'us-east-1'),
    'version' => 'latest',
    'ua_append' => [
        'L5MOD/' . AwsServiceProvider::VERSION,
    ],

環境設定ファイルにアクセスキーとシークレットキーを設定

.env
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=

コマンドでバッチファイル作成

php artisan make:command SendSms

以下にバッチファイルが作成されるので必要なところを編集

app/Console/Commands/SendSms.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;

class SendSms extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:sms {tel}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'sms送信';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // パッケージ呼び出し
        $sns = App::make('aws')->createClient('sns');

        // 引数の値を取得
        $tel = $this->argument("tel");

        // メッセージ作成
        $msg = 'テスト送信';

        // 送信
        $sns->publish([
            'Message' => $msg,
            'PhoneNumber' => '+81' . mb_substr($tel, 1), // 電話番号は国際電話番号表記に変更
            'MessageAttributes' => [
                'AWS.SNS.SMS.SenderID' => [
                    'DataType' => 'String',
                    'StringValue' => 'APP_NAME' // <- 表示名
                ]
            ]
        ]);
    }
}

コマンドから送信する場合

php artisan send:sms --tel=090123456789

コントローラーから送信する場合

\Artisan::call('send:sms', [
    'tel' => $tel
]);
3
0
1

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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?