如何使用PHP AWS SDK在Symfony应用程序中发送短信

160 阅读1分钟

在这个例子中,我们将处理亚马逊简单通知服务(SNS),向手机发送短信。

安装

运行composer require aws/aws-sdk-php ,安装AWS SDK for PHP库。

配置AWS SNS

进入 "身份和访问管理 "仪表板,通过分配 "AmazonSNSFullAccess "策略添加一个新用户。secret ,在创建新用户时只能看到一次,所以请确保在安全的地方记下它。还要确保该用户不能像普通人那样登录AWS,所以 "组 "应该是 "无",而不是像 "AdministratorAccess "这样的东西。

文件

parameters.yml

parameters:
    aws_sdk.config.default:
        version: 'latest'
        region: 'eu-west-1'

    aws_sdk.credentials.default:
        credentials:
            key: 'AWS_KEY'
            secret: 'AWS_SECRET'

services.yml

services:
    Aws\Sdk: ~

    App\Util\AwsSnsUtil:
        arguments:
            $config: '%aws_sdk.config.default%'
            $credentials: '%aws_sdk.credentials.default%'

AwsSnsUtilInterface

declare(strict_types=1);

namespace App\Util;

interface AwsSnsUtilInterface
{
    public function sendSms(string $phoneNumber): bool;
}

AwsSnsUtil

配置细节可以在这里找到。

declare(strict_types=1);

namespace App\Util;

use Aws\Sdk;
use Aws\Sns\Exception\SnsException;

class AwsSnsUtil implements AwsSnsUtilInterface
{
    private $client;

    public function __construct(Sdk $sdk, iterable $config, iterable $credentials)
    {
        $this->client = $sdk->createSns($config+$credentials);
    }

    public function sendSms(string $phoneNumber): bool
    {
        try {
            $this->client->publish([
                'PhoneNumber' => $phoneNumber,
                'Message' => 'Feeds have been processed!',
                'MessageAttributes' => [
                    'AWS.SNS.SMS.SenderID' => [
                        'DataType' => 'String',
                        'StringValue' => 'INANZZZ'
                    ],
                    'AWS.SNS.SMS.SMSType' => [
                        'DataType' => 'String',
                        'StringValue' => 'Promotional'
                    ],
                ],
            ]);

            $result = true;
        } catch (SnsException $e) {
            $result = false;
        }

        return $result;
    }
}

测试

$this->awsSnsUtil->sendSms('0044_rest_of_the_number');

测试结果