<?php
namespace app\api\controller;
use AlibabaCloud\Client\DefaultAcsClient;
use AlibabaCloud\Client\Profile\DefaultProfile;
use AlibabaCloud\Dysmsapi\Dysmsapi;
use AlibabaCloud\Dysmsapi\V20170525\SendSms;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use think\Controller;
use think\Hook;
/**
* 手机短信接口
*/
class Sms extends Controller
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
/**
* 发送验证码
*
* @param string $mobile 手机号
* @param string $event 事件名称
*/
public function send()
{
$mobile = $this->request->post("mobile");
$event = $this->request->post("event");
$event = $event ? $event : 'editpassword';
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 60) {
return json_code(-200,'发送频繁');
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
return json_code(-200,'发送频繁');
}
$ret = $this->send($mobile, null, $event);
if ($ret) {
return json_code(200,'发送成功');
} else {
return json_code(-200,'发送失败');
}
}
/**
* 发送验证码
*
* @param int $mobile 手机号
* @param int $code 验证码,为空时将自动生成4位数字
* @param string $event 事件
* @return boolean
*/
public function send($mobile, $code = null, $event = 'default')
{
$code = is_null($code) ? mt_rand(1000, 9999) : $code;
$time = time();
$ip = request()->ip();
);
$result=$this->main($mobile,$code);
if ($result->body->code==='OK') {
$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
return true;
}
return false;
}
public function createClient($accessKeyId, $accessKeySecret){
$config = new \Darabonba\OpenApi\Models\Config([
// 您的AccessKey ID
"accessKeyId" => $accessKeyId,
// 您的AccessKey Secret
"accessKeySecret" => $accessKeySecret
]);
// 访问的域名
$config->endpoint = "dysmsapi.aliyuncs.com";
return new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
}
public function main($mobile,$code){
$client = $this->createClient("您的AccessKey ID", "您的AccessKey Secret");
$sendSmsRequest = new SendSmsRequest([
"phoneNumbers" => $mobile,
"signName" => "所思物联网",
"templateCode" => "SMS_152655630",
"templateParam" => "{'code':$code}"
]);
// 复制代码运行请自行打印 API 的返回值
$res=$client->sendSms($sendSmsRequest);
return $res;
}
}
composer 安装?composer require alibabacloud/dysmsapi-20170525 1.0.2
|