Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions src/Utopia/Messaging/Adapter/SMS/AlibabaCloud.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

namespace Utopia\Messaging\Adapter\SMS;

use Utopia\Messaging\Adapter\SMS as SMSAdapter;
use Utopia\Messaging\Messages\SMS as SMSMessage;
use Utopia\Messaging\Response;

class AlibabaCloud extends SMSAdapter
{
protected const NAME = 'AlibabaCloud';

/**
* @param string $accessKeyId Alibaba Cloud Access Key ID
* @param string $accessKeySecret Alibaba Cloud Access Key Secret
* @param string $signName Alibaba Cloud SMS Sign Name
* @param string $templateCode Alibaba Cloud SMS Template Code
*/
public function __construct(
private string $accessKeyId,
private string $accessKeySecret,
private string $signName,
private string $templateCode,
) {
}

/**
* Get adapter name.
*/
public function getName(): string
{
return static::NAME;
}

/**
* Get max messages per request.
*/
public function getMaxMessagesPerRequest(): int
{
return 1;
}

/**
* {@inheritdoc}
*/
protected function process(SMSMessage $message): array
{
$response = new Response($this->getType());

foreach ($message->getTo() as $to) {
$params = [
'AccessKeyId' => $this->accessKeyId,
'Action' => 'SendSms',
'Format' => 'JSON',
'PhoneNumbers' => $to,
'RegionId' => 'cn-hangzhou',
'SignName' => $this->signName,
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce' => \uniqid(),
'SignatureVersion' => '1.0',
'TemplateCode' => $this->templateCode,
'TemplateParam' => \json_encode(['code' => $message->getContent()]),
'Timestamp' => \gmdate('Y-m-d\TH:i:s\Z'),
'Version' => '2017-05-25',
];

$params['Signature'] = $this->generateSignature($params);

$queryString = '';
foreach ($params as $key => $value) {
$queryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
}
$queryString = \substr($queryString, 1);

$result = $this->request(
method: 'GET',
url: 'https://dysmsapi.aliyuncs.com?' . $queryString,
headers: [],
body: null
);

if ($result['statusCode'] >= 200 && $result['statusCode'] < 300 && ($result['response']['Code'] ?? '') === 'OK') {
$response->incrementDeliveredTo();
$response->addResult($to);
} else {
$response->addResult($to, $result['response']['Message'] ?? 'Unknown error');
}
}

return $response->toArray();
}

/**
* Generate Alibaba Cloud API Signature.
*/
private function generateSignature(array $params): string
{
\ksort($params);

$canonicalizedQueryString = '';
foreach ($params as $key => $value) {
$canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
}

$stringToSign = 'GET&' . $this->percentEncode('/') . '&' . $this->percentEncode(\substr($canonicalizedQueryString, 1));

$signature = \base64_encode(\hash_hmac('sha1', $stringToSign, $this->accessKeySecret . '&', true));

return $signature;
}

private function percentEncode(string $str): string
{
$res = \urlencode($str);
$res = \str_replace(['+', '*'], ['%20', '%2A'], $res);
$res = \preg_replace('/%7E/i', '~', $res);

return $res;
}
}
32 changes: 32 additions & 0 deletions tests/Messaging/Adapter/SMS/AlibabaCloudTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Utopia\Tests\Adapter\SMS;

use Utopia\Messaging\Adapter\SMS\AlibabaCloud;
use Utopia\Messaging\Messages\SMS;
use Utopia\Tests\Adapter\Base;

class AlibabaCloudTest extends Base
{
/**
* @throws \Exception
*/
public function testSendSMS(): void
{
$sender = new AlibabaCloud(
\getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
\getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
\getenv('ALIBABA_CLOUD_SIGN_NAME'),
\getenv('ALIBABA_CLOUD_TEMPLATE_CODE')
);

$message = new SMS(
to: [\getenv('ALIBABA_CLOUD_TO')],
content: \json_encode(['code' => '123456']),
);

$result = $sender->send($message);

$this->assertResponse($result);
}
}