赞
踩
1、导入阿里短信包
通过composer下载依赖包
composer require alibabacloud/dysmsapi-20170525 2.0.22
具体可参见阿里云短信服务 >> 快速学习
2、编写发送短信程序
- class Index
- {
- private $log;
- public function index(){
- //需要发送的用户数组
- $users=[
- [
- 'mobile' => '手机号码',
- 'name' => '姓名'
- ]
- ];
-
- foreach ($users as $user){
- //手机
- $mobile = $user['mobile'];
- //姓名
- $name = $user['name'];
-
- //短信参数
- $params = [
- 'name' => $name,//姓名
- ];
-
- //发送短信
- $this->sendSms($mobile,'阿里云短信模板编号',$params);
- }
- }
- //发送短信
- private function sendSms($mobile,$smsCode,$params=''){
- //手机号码
- $phone = trim($mobile);
-
- $data = [
- 'templateCode' => $smsCode,//短信模板编号
- 'phone' => $phone,//手机号码
- //短信参数
- 'params' => $params
- ];
-
- //调用阿里云短信发送方法
- $result = Alicode\AliSms::main($data);
- }
- }
extend目录创建Alicode/AliSms类
- namespace Alicode;
- use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
-
- use Darabonba\OpenApi\Models\Config;
- use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
-
-
- class AliSms
- {
- /**
- * 使用AK&SK初始化账号Client
- * @param string $accessKeyId
- * @param string $accessKeySecret
- * @return Dysmsapi Client
- */
- public static function createClient(string $accessKeyId, string $accessKeySecret): Dysmsapi
- {
- $config = new Config([
- // 您的AccessKey ID
- "accessKeyId" => $accessKeyId,
- // 您的AccessKey Secret
- "accessKeySecret" => $accessKeySecret
- ]);
- // 访问的域名
- $config->endpoint = "dysmsapi.aliyuncs.com";
- return new Dysmsapi($config);
- }
-
- /**
- * @param string[] $args
- * @return void
- */
- public static function main(array $args)
- {
- $client = self::createClient("LTAI5tSSAjCaVBxKPbMeoXb6", "KCwxkcnplJThtPOwBh0Mc8xvDolp8w");
-
- //签名
- $signName='你的签名';
- //短信参数
- $templateParam=$args['params'];
- if(!empty($templateParam)){
- //有参数
- $sendSmsRequest = new SendSmsRequest([
- "phoneNumbers" => $args['phone'],
- "signName" => $signName,
- "templateCode" => $args['templateCode'],
- "templateParam" => json_encode($templateParam)
- ]);
- }else{
- //无参数
- $sendSmsRequest = new SendSmsRequest([
- "phoneNumbers" => $args['phone'],
- "signName" => $signName,
- "templateCode" => $args['templateCode'],
- ]);
- }
-
-
- $result = $client->sendSms($sendSmsRequest);
- if ($result->body->message == 'OK' && $result->body->code == 'OK') {
- return ['code' => 200,'msg'=>'success'];
- }
- if ($result->body->code == 'isv.MOBILE_NUMBER_ILLEGAL') {
- return ['code' => 0, 'msg' => '手机号码格式不正确'];
- }
- return ['code' => 0, 'msg' => '短信发送失败,网络繁忙'];
- }
- }
3、设置定时任务
crontab -e
写入以下信息:比如我是设定每天10点发送
0 10 * * * /usr/bin/curl 你的网址
然后,开启定时服务
systemctl start crond.service
如果已经开启,则重启
systemctl restart crond.service
查看定时任务
crontab -l
实时监控日志
tail -f /var/log/cron
退出tail:Ctrl + C
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。