首页 > 技术文章 > TP5.1 阿里云短信

zyfeng 2020-12-02 13:07 原文

插件合集

点击跳转

安装

composer require alibabacloud/sdk

后台

<?php
/**
 * Created by PhpStorm.
 * User: Zhangyongfeng
 * Date: 2020/11/24
 * Time: 13:57
 *
 * ━━━━━━━━━神兽出没━━━━━━━━━
 *
 *        ┏┓   ┏┓+ +
 *       ┏┛┻━━━┛┻┓ + +
 *       ┃       ┃  
 *       ┃   ━   ┃ ++ + + +
 *       ████━████ ┃+
 *       ┃       ┃ +
 *       ┃   ┻   ┃
 *       ┃       ┃ + +
 *       ┗━┓   ┏━┛
 *         ┃   ┃           
 *         ┃   ┃ + + + +
 *         ┃   ┃    Code is far away from bug with the animal protecting       
 *         ┃   ┃ +     神兽保佑,代码无bug  
 *         ┃   ┃
 *         ┃   ┃  +         
 *         ┃    ┗━━━┓ + +
 *         ┃        ┣┓
 *         ┃        ┏┛
 *         ┗┓┓┏━┳┓┏┛ + + + +
 *          ┃┫┫ ┃┫┫
 *          ┗┻┛ ┗┻┛+ + + +
 *
 * ━━━━━━━━━感觉萌萌哒━━━━━━━━━
 */

namespace app\base\controller;

use think\App;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class TelCode extends Base
{
    protected $alConfig = [];

    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->alConfig = [
            'accessKeyId' => $this->config['cfg_alicloudid'],
            'accessKeySecret' => $this->config['cfg_alicloudsecret'],
            'product' => 'Dysmsapi',
            'version' => '2017-05-25',
            'action' => 'SendSms',
            'method' => 'POST',
            'host' => 'dysmsapi.aliyuncs.com',
            'signName' => $this->config['cfg_alicloudname'],
            'templateCode' => $this->config['cfg_alicloudmodel'],
        ];
    }

    /**
     * [alGetcode 获取阿里云验证码]
     * @param number $tel 手机号
     * @param string $signName 签名(需要在阿里云短信服务后台申请)
     * @param string $templateCode 短信模板code (需要在阿里云短信服务后台申请)
     * @param boolean $debug 是否试调
     * @return array ['msg' => 123456, 'code' => 1001]
     * @return array ['msg' => '手机号错误', 'code' => 500]
     * */
    function alGetcode($tel, $signName = "", $templateCode = "", $debug = false)
    {
        if(is_null($tel)){ return parent::showReturnCode(500, '','手机号为空'); }
        if(empty($signName)){ $signName = $this->alConfig['signName']; }
        if(empty($templateCode)){ $templateCode = $this->alConfig['templateCode']; }
        $check = '/^(1(([35789][0-9])|(47)))\d{8}$/';
        if (preg_match($check, $tel)) {
            $code = rand(100000,999999);
            session('code', $code, 'index');
            if($debug){ echo session('code', '', 'index');die; }
            AlibabaCloud::accessKeyClient($this->alConfig['accessKeyId'], $this->alConfig['accessKeySecret'])
                ->regionId('cn-hangzhou')
                ->asDefaultClient();
            try {
                $result = AlibabaCloud::rpc()
                    ->product($this->alConfig['accessKeyId'])
                    ->version($this->alConfig['version'])
                    ->action($this->alConfig['action'])
                    ->method($this->alConfig['method'])
                    ->host($this->alConfig['host'])
                    ->options([
                        'query' => [
                            'RegionId' => "cn-hangzhou",
                            //需要发送到那个手机
                            'PhoneNumbers' => $tel,
                            //必填项 签名(需要在阿里云短信服务后台申请)
                            'SignName' => $signName,
                            //必填项 短信模板code (需要在阿里云短信服务后台申请)
                            'TemplateCode' => $templateCode,
                            //如果在短信中添加了${code} 变量则此项必填 要求为JSON格式
//                        'TemplateParam' => "{'code':".$a."}",
                        ],
                    ])
                    ->request();
            } catch (ClientException $e) {
//                    echo $e->getErrorMessage() . PHP_EOL;
            } catch (ServerException $e) {
//                    echo $e->getErrorMessage() . PHP_EOL;
            }
            return parent::showReturnCode(1001, session('code', '', 'index'), '验证码校验通过');
        } else {
            return parent::showReturnCodeWithOutData(500, '手机号错误');
        }
    }

    /**
     * [changeAlCode 校验阿里云验证码]
     * @param number $code
     * @return array ['msg' => '验证码校验通过', 'code' => 1001]
     * @return array ['msg' => '验证码校验失败', 'code' => 501]
     * */
    public function changeAlCode($code)
    {
        if($code == session('code', '', 'index')){
            return parent::showReturnCodeWithOutData(1001, '验证码校验通过');
        }else{
            return parent::showReturnCodeWithOutData(500, '验证码校验失败');
        }
    }


}

 

其中 showReturnCode 方法可以自定义,原型是['code' => 1001, 'msg'=> '成功']

 前端

<div class="layui-fluid">
    <div class="layui-row">
        <form class="layui-form" method="post">

            <div class="layui-form-item">
                <label class="layui-form-label">手机号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="tel" name="tel" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">短信验证码:</label>
                <div class="layui-input-inline">
                    <input type="text" id="code" name="code" autocomplete="off" class="layui-input">
                    <button type="button" class="layui-btn" onclick="getCode(this)">获取验证码(阿里云)</button>
                </div>
            </div>

            <div class="layui-form-item">
                <label for="L_repass" class="layui-form-label"></label>
                <button class="layui-btn" >提交</button>
            </div>

        </form>
    </div>
</div>

JS

  var flag = true;
    // 获取验证码
    function getCode(obj){
        if(!flag){ return}
        var tel = $("#tel").val()
        var telreg = /^1\d{10}$/

        if (!telreg.test(tel) || (tel == "" || tel == null)) {
            layer.msg('请输入正确的手机号码', {icon:2,time:2000})
            $("#tel").focus()
            return false
        }else{
            var number = 60;
            var c_time = setInterval(function(){
                if(number <= 1){
                    flag = true
                    $(obj).html("重新发送");
                    clearInterval(c_time);
                }else{
                    flag = false
                    $(obj).html("重新发送("+number+")")
                    number--
                }
            },1000);
            $.ajax({
                url:"<{:url('telCode')}>",
                type:"POST",
                data:{
                    tel: tel,
                    signName: "",
                    templateCode: "",
                    debug: true
                },
                success:function(data){
                    console.log(data);
                }
            })
        }
    }

调用

   public function telCode()
    {
        if(request()->post()){
            if(!empty($this->param['tel'])){ $tel = $this->param['tel']; }else { return parent::showReturnCodeWithOutData(500, '手机号错误'); }
            $signName = !empty($this->param['signName']) ? $this->param['signName'] : '';
            $templateCode = !empty($this->param['templateCode']) ? $this->param['templateCode'] : '';
            return $this->telCode->alGetcode($tel, $signName, $templateCode, $this->param['debug']);
        }
        return $this->fetch();
    }

效果

 

推荐阅读