阿里云短信代码

重要代码在最后面,前面是一些判断步骤,可直接省略

注释突出的地方需要注意,看注释!!!

<!--    阿里短信    -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.4</version>
        </dependency>

import back.minsu.entity.Codes;
import back.minsu.param.UserParam;
import back.minsu.service.UserService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author: zyh
 * @Description:短信验证码
 */
@Configuration
@RequestMapping(value = "code")
@RestController
public class CodeUtils {

    @Autowired
    UserService userService;

    /**
     * @Description:验证码次数清空
     * 创建定时任务,每天0点0时自动执行
     */
//    @Scheduled(cron = "0 0 0 * * ? ")
//    @PostMapping(value = "delNum")
//    public Result delNum(){
//        return  userService.delNum();
//    }

    /**
     * @params:phone
     * @Description:生成短信验证码
     * @return:code
     */
    @PostMapping(value = "/generateCode")
    public Result generateCode(@RequestBody UserParam param) throws Exception {
        String phone = param.getPhone();
        if(phone == null && phone.equals("")){
            return Result.error("请输入手机号");
        }
        Codes appCodeApi = userService.getCode(phone);
        //获取时间,判断是否在1分钟内
        if (StringUtils.isEmpty(appCodeApi)){
            String code = aliCode(param.getPhone());//调用生成验证码的方法
            param.setCode(code);
            param.setNum(1);//将次数设置为1
            userService.saveCode(param);//添加请求记录,code表
        } else {
            System.out.println(123);
            Date obtainTime = appCodeApi.getAddTime();//获取上次请求验证码的时间
            if (new Date().getTime() - obtainTime.getTime() < 60*1000){
                return Result.error("1分钟内只能请求一次");//在一分钟内,直接return,禁止请求
            }
            if (appCodeApi.getNum() >= 5){
                return Result.error("获取验证码次数过多!").build("count",appCodeApi.getNum());
            } else {
                String code = aliCode(param.getPhone());//调用生成验证码的方法
                appCodeApi.setCode(code);
                appCodeApi.setNum(appCodeApi.getNum() + 1);
                userService.saveCode1(appCodeApi);//添加请求记录,code表
            }
        }
        return Result.ok("state","获取成功").build("count",(appCodeApi != null ? appCodeApi.getNum() : 1));
    }

    /**
     * @params:phone,code
     * @Description:判断短信验证码是否正确
     * @return:status
     */
    public boolean checkCode(String phone, String code) {
        boolean res = true;
        UserParam appCodeApi = userService.selectPhone(phone);
        if (appCodeApi != null) {
            if (appCodeApi.getCode().equals(code)) {
                if (System.currentTimeMillis() > appCodeApi.getAddTime().getTime()+5*60*1000) {
                    res = false;
                }
            } else {
                res = false;
            }
        } else {
            res = false;
        }
        return res;
    }


    public String aliCode(String phone) throws ClientException {
        //生成用于验证码的随机码
        int codeInt = (int)((Math.random()*9+1)*100000);
        String i = String.valueOf(codeInt);

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
//替换成你的AK
        final String accessKeyId = "***********************";//你的accessKeyId,参考本文档步骤2
        final String accessKeySecret = "***********************";//你的accessKeySecret,参考本文档步骤2
//初始化ascClient,暂时不支持多region(请勿修改)
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);



        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("小牛邦");
        //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
        request.setTemplateCode("SMS_187105350");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParam("{\"code\":\""+i+"\"}");
        //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        System.out.println("code:"+request.getTemplateParam());
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            System.out.println("短信发送成功!");
        }else {
            System.out.println("短信发送失败!");
        }
        return String.valueOf(i);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 PHP 发送阿里云短信的示例代码: ```php // 替换成你的 AccessKeyId 和 AccessKeySecret $accessKeyId = "your_access_key_id"; $accessKeySecret = "your_access_key_secret"; // 签名和模板编号 $signName = "your_sign_name"; $templateCode = "your_template_code"; // 手机号码和验证码 $phoneNumbers = "18888888888"; $verifyCode = "123456"; // 构建请求参数 $params = array ( "code" => $verifyCode ); // 发起请求 $helper = new SmsHelper($accessKeyId, $accessKeySecret); $response = $helper->send($phoneNumbers, $signName, $templateCode, $params); // 处理响应结果 if ($response->Code == 'OK') { // 发送成功 } else { // 发送失败 } // SmsHelper 类定义 class SmsHelper { private $accessKeyId; private $accessKeySecret; private $serverUrl = "http://dysmsapi.aliyuncs.com"; public function __construct($accessKeyId, $accessKeySecret) { $this->accessKeyId = $accessKeyId; $this->accessKeySecret = $accessKeySecret; } public function send($phoneNumbers, $signName, $templateCode, $params) { $paramsJson = json_encode($params); $paramsArray = array ( "PhoneNumbers" => $phoneNumbers, "SignName" => $signName, "TemplateCode" => $templateCode, "TemplateParam" => $paramsJson, "RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25" ); $paramsString = http_build_query($paramsArray); $signature = $this->computeSignature($paramsArray); $url = "{$this->serverUrl}/?Signature={$signature}&{$paramsString}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch); return json_decode($response); } private function computeSignature($params) { ksort($params); $canonicalQueryString = http_build_query($params); $stringToSign = "GET&%2F&" . urlencode($canonicalQueryString); $signature = base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true)); return urlencode($signature); } } ``` 在上面的代码中,`SmsHelper` 类封装了发送短信的方法,其中 `send` 方法接受手机号码、签名、模板编号和消息参数作为参数,返回一个响应对象。你只需要将代码中的占位符替换成你自己的参数即可在你的应用程序中使用这个类发送短信
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值