简单的阿里云短信发送类库

类库代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php
/**
* Created by PhpStorm.
* User: 小灰灰
* Date: 2023-10-08
* Time: 10:58:58
* Info: 阿里云短信发送插件
*/

namespace support\lib;

class AliSms
{

protected $error;

protected $accessKeyId;

protected $accessKeySecret;

public function __construct($accessKeyId, $accessKeySecret)
{
$this->accessKeyId = ! empty($accessKeyId) ? $accessKeyId : '';
$this->accessKeySecret = ! empty($accessKeySecret) ? $accessKeySecret : '';
}

public function getError()
{
return $this->error;
}

/**
* 发送短信
*/
public function sendSms($params = array())
{
if (empty($params['PhoneNumbers'])) {
throw new \InvalidArgumentException('缺失手机号$params["PhoneNumbers"]');
}
if (empty($params['SignName'])) {
throw new \InvalidArgumentException('缺失短信签名$params["SignName"]');
}
if (empty($params['TemplateCode'])) {
throw new \InvalidArgumentException('缺失模版CODE$params["TemplateCode"]');
}

// fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
$accessKeyId = $this->accessKeyId;
$accessKeySecret = $this->accessKeySecret;

// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
if ( ! empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
$params["TemplateParam"] = json_encode($params["TemplateParam"]);
}

try {
$content = $this->request($accessKeyId, $accessKeySecret, "dysmsapi.aliyuncs.com",
array_merge($params, array(
"RegionId" => "cn-hangzhou",
"Action" => "SendSms",
"Version" => "2017-05-25",
)));
if ($content->Code == 'OK') {
return true;
} else {
throw new \InvalidArgumentException($content->Message);
};
} catch (\Exception $e) {
throw new \InvalidArgumentException($e->getMessage());
}
}

/**
* 生成签名并发起请求
*
* @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
* @param $accessKeySecret string AccessKeySecret
* @param $domain string API接口所在域名
* @param $params array API具体参数
*
* @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false
*/
public function request($accessKeyId, $accessKeySecret, $domain, $params)
{
$apiParams = array_merge(array(
"SignatureMethod" => "HMAC-SHA1",
"SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
"SignatureVersion" => "1.0",
"AccessKeyId" => $accessKeyId,
"Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
"Format" => "JSON",
), $params);
ksort($apiParams);

$sortedQueryStringTmp = "";
foreach ($apiParams as $key => $value) {
$sortedQueryStringTmp .= "&".$this->encode($key)."=".$this->encode($value);
}

$stringToSign = "GET&%2F&".$this->encode(substr($sortedQueryStringTmp, 1));

$sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret."&", true));

$signature = $this->encode($sign);

$url = "http://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

try {
$content = $this->fetchContent($url);

return json_decode($content);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}

private function encode($str)
{
$res = urlencode($str);
$res = preg_replace("/\+/", "%20", $res);
$res = preg_replace("/\*/", "%2A", $res);
$res = preg_replace("/%7E/", "~", $res);

return $res;
}

private function fetchContent($url)
{
if (function_exists("curl_init")) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"x-sdk-client" => "php/2.0.0"
));
$rtn = curl_exec($ch);

if ($rtn === false) {
trigger_error("[CURL_".curl_errno($ch)."]: ".curl_error($ch), E_USER_ERROR);
}
curl_close($ch);

return $rtn;
}

$context = stream_context_create(array(
"http" => array(
"method" => "GET",
"header" => array("x-sdk-client: php/2.0.0"),
)
));

return file_get_contents($url, false, $context);
}

}

发送服务代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/**
* Created by PhpStorm.
* User: 小灰灰
* Date: 2023-10-08
* Time: 11:01:34
* Info:
*/

namespace app\common\service;

use support\lib\AliSms;

class SmsCodeService extends AliSms
{

private $access_key = '';

private $access_secret = '';

//签名
const SIGN_NAME = '';

//短信模板代码
const TEMPLATE_SMS_CODE = '';

public function __construct()
{
parent::__construct($this->access_key, $this->access_secret);
}

public function sendSmsCode(array $param)
{
$query = [
'SignName' => self::SIGN_NAME,
'TemplateCode' => self::TEMPLATE_SMS_CODE
];

$query = array_merge($query, $param);

return $this->sendSms($query);
}

}

调用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use app\common\service\SmsCodeService;


public function send_sms()
{

$phone = request()->get('phone');
if (empty($phone)) {
return $this->error('手机号不能为空');
}
if (cmf_check_mobile($phone)) {
$sms_code = rand(100000, 999999);
$param = [
'PhoneNumbers' => $phone,
'TemplateParam' => json_encode(['code' => $sms_code])
];
$smsServie = new SmsCodeService();
try {
$result = $smsServie->sendSmsCode($param);
if ( ! $result) {
return $this->error('发送失败');
}

return $this->success('发送成功');

} catch (\Exception $e) {
return $this->error($e->getMessage());
}
} else {
return $this->error("请输入正确手机号");
}

}