tp5 阿里大于短信

按照文档来就行了。
最低要求 PHP 5.6
安装 SDK 核心库 OpenAPI ,如果已在系统上全局安装 Composer,请直接在项目目录中运行以下内容来安装 Alibaba Cloud SDK for PHP 作为依赖项:

composer require alibabacloud/darabonba-openapi

⚠️注意:执行 composer 安装 SDK 的 PHP 版本要小于或等于实际运行时的 PHP 版本。 例如,在 PHP7.2 环境下安装 SDK 后生成 vendor 目录,只能在 PHP7.2 以上版本使用,如果拷贝到 PHP5.6 环境下使用,会出现依赖版本不兼容问题。
一些用户可能由于网络问题无法安装,可以通过以下命令使用阿里云 Composer 全量镜像。

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

Packagist

composer require alibabacloud/dysmsapi-20170525 2.0.23

最后一步安装不成功可能是因为没有23版本,安装20得也可以,下面是Alibaba_sms.php

<?php

namespace app\common\server;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use think\Env;

class Alibaba_sms {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填,您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填,您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 使用STS鉴权方式初始化账号Client,推荐此方式。本示例默认使用AK&SK方式。
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @param string $securityToken
     * @return Dysmsapi Client
     */
    public static function createClientWithSTS($accessKeyId, $accessKeySecret, $securityToken){
        $config = new Config([
            // 必填,您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填,您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret,
            // 必填,您的 Security Token
            "securityToken" => $securityToken,
            // 必填,表明使用 STS 方式
            "type" => "sts"
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 发送验证码
     * @param $args
     * @return \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse|void
     */
    public static function main($args){
        extract($args);
        $client = self::createClient(Env::get('alibabasms.accessKeyId'), Env::get('alibabasms.accessKeySecret'));
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => Env::get('alibabasms.signName'),
            "templateCode" => Env::get('alibabasms.TemplateCode'),
            "templateParam" => $templateParam, // 验证码字符串
        ]);
        $runtime = new RuntimeOptions([]); // 可忽略
        try {
            // 复制代码运行请自行打印 API 的返回值
            $resp = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            return $resp;
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要,请打印 error
            Utils::assertAsString($error->message);
        }
    }
}

Api

/**
     * 发送验证码
     * @return void
     * @throws \think\Exception
     */
    public function alidayusms_send(){
        $phone = $this->request->param('phone');
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';

        if (!$phone || !\think\Validate::regex($phone, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($phone, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        //生成验证码
        $code = Random::numeric(config('captcha.length'));
        // 阿里云规定必须json字符串
        $templateParam = json_encode(['code'=>$code]);
        $data = [
            'phone' => $phone, // 手机号
            'templateParam' => $templateParam, // 验证码字符串
            'event' => $event,
        ];
        $ret = Alibaba_sms::main($data);
        $ret = json_decode(json_encode($ret,true),true);
        if ($ret['statusCode'] == 200 && $ret['body']['code'] == "OK" && $ret['body']['message'] == "OK") {
            $time = time();
            $ip = request()->ip();
            $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $phone, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败'));
        }

    }

检测验证码有效性

	/**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 300;
    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;
	/**
     * @param $mobile
     * @param $code
     * @param $event
     * @return array|false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function alisms_check($mobile, $code, $event = 'default'){
        $time = time() - self::$expire;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                } else {
                    $result = true;
                    return $result;
                }
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间轴-小文同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值