2
2

More than 1 year has passed since last update.

AWS SNS HTTP/HTTPSのサブスクリプションを確認する方法 on Laravel

Last updated at Posted at 2022-04-26

AWS SNS HTTP/HTTPSのサブスクリプションを確認する方法 on Laravel

追加した、サブスクリプションが「保留中の確認」になったあと
「確認済み」にする方法の情報が非常に少なかったのでメモ
Laravelで記載しますが、他の言語でも同じだと思います。

エンドポイントは以下を設定したとする

https://sns.test.com/sns/notification

Laravel側

CSRF対策が設定されていると、HTTP 419などになるので
サブスクリプションを確認する場合は、認証なしで受け付ける必要があります。

apiでもwebでもどちらでも良いですが、認証なしで!

下記の例では、webの方は、VerifyCsrfTokenが効いているので、apiの方を使う必要がある

App\Http\Kernel.php
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:24000,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

POST通信で来ます!

routes/api.php
Route::post('/notification', 'SNSNotificationController@notification');

リクエストを解析して、SubscribeURLへリクエストを投げます!

サブスクリプションを確認するリクエストと、運用後の通知で処理を分岐させます。

SubscribeURLのURLにアクセスすると、サブスクリプションを確認することができます。
もしくは、SubscribeURLをブラウザで開いてもOKです。

ちなみに、SubscribeURLは以下のような形です。

https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn={$payload->TopicArn}&Token={$payload->Token}

App\Http\Controllers\SNSNotificationController.php
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class SNSNotificationController extends Controller
{
    public function notification(Request $request)
    {
        // SNSからのリクエストを受信
        $payload = json_decode($request->getContent());
        if(property_exists($payload, 'Type')){
          if($payload->Type === "SubscriptionConfirmation")
          {
              // このエンドポイントでの通知サブスクリプションを確認
              // 初めての場合は、SubscribeURLのURLにアクセスしてサブスクリプションを確認します。
              $confirmation_url = curl_init($payload->SubscribeURL);
              curl_exec($confirmation_url);
          } elseif($payload->Type === 'Notification'){
                // SNSからの通知が来た時の処理
          }
        }
    }
}

管理コンソールで確認すれば、「確認済み」となっているはずです!

それでは、素晴らしいAWSライフを! おしまい

2
2
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
2
2