[aws/php] AWS SDK for PHP + AWS SNSを使用してAPNsをiOSデバイスに送信する方法
AWS SDK for PHP + AWS SNSを使用してAPNsをiOSデバイスに送信する方法は以下の通り
前提条件:アプリ側、AWS SNSなどの通知環境は既に構築済みとする
通知環境構築は下記記事参照
[AWS/Swift4] AWS SNS + Cognito + iOS10でサーバレスでAPNsをpushする方法
目次
AWS SDK for PHPの導入
bitnamiのphp環境にAWS SDK for PHPを導入する
通知を実行するファイルの横、もしくは~/apps/wordpress/htdocsに移動する
Composerを使用してインストール
curl -sS https://getcomposer.org/installer | php
php composer.phar require aws/aws-sdk-php
正常にインストールされると、コマンドを発行したフォルダにvenderというフォルダができているはず。
phpコード
APNs通知発行依頼をAWS SNSに対して発行するには以下のコードを実装
前もって、AWS SNSに対してアクセス権を持っているAWS IAMユーザを作成しておき、アクセスキー・シークレットキーを発行しておく。
<?php
require 'vendor/autoload.php';
use Aws\Sns\SnsClient;
$sns = SnsClient::factory(array(
'version' => 'latest',
'key' => 'AWS SNSへのアクセス権を持っているIAMのアクセスキー',
'secret' => 'AWS SNSへのアクセス権を持っているIAMのシークレットキー',
'region' => 'ap-northeast-1'//リージョン名
));
$iOS_AppArn = 'AWS SNSのアプリケーションARN';
$iOS_model = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $iOS_AppArn));
//通知メッセージ
$alert="AWS SNSより発行";
// それぞれのエンドポイントへメッセージを送る
foreach ($iOS_model['Endpoints'] as $endpoint)
{
$endpointArn = $endpoint['EndpointArn'];
try
{
$sns->publish(array(
'TargetArn' => $endpointArn,
'MessageStructure' => 'json',
'Message' => json_encode(array(
'APNS_SANDBOX' => json_encode(array(
'aps' => array(
'alert' => $alert,
'sound' => 'default',
'badge' => 1
),
// カスタム
'custom_text' => "カスタムテキスト",
))
))
));
echo "ok";
}
catch (Exception $e)
{
$e->getMessage();
}
}
?>
ブラウザで該当ファイルにアクセスすると通知が飛ぶ。
ちなみに「$sns->listEndpointsByPlatformApplication」で取得できるendpoint数は100が最大で、100以上endpointが登録されている場合は、返り値に「NextToken」が付いている。
そのNextTokenを指定して再度取得すると次の100件のendpointが取得できる。
do {
// We only get 100 subscribers, if there's a nextToken, get the next 100
if( $nextToken ) {
$result = $client->listEndpointsByPlatformApplication(array(
'PlatformApplicationArn' => $gcm_arn,
'NextToken' => $nextToken
));
} else {
// Run this the first time, since there's no nextToken yet
$result = $client->listEndpointsByPlatformApplication(array(
'PlatformApplicationArn' => $gcm_arn
));
}
$nextToken = $result['NextToken'];
} while( $nextToken );
参考:https://gist.github.com/scottopolis/df0e42b02c39564dc21b