【阿里短信发送DEMO】阿里短信发送获取验证码

代码可以用,希望能帮到你


import io.seata.common.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import net.sf.json.JSONObject;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/rest/Sms")
@Api(tags = "短信服务 控制层")
public class SmsController {

    private final static Logger logger = LoggerFactory.getLogger(SmsController.class);
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "获取手机验证码", notes = "获取手机验证码")
    @RequestMapping(value = "phoneCode", method = RequestMethod.GET)
    public RestResponse phoneCode(@RequestParam String phone,
                                  @RequestParam String areaCode) {
        if (StringUtils.isBlank(phone)) return RestResponse.failed("手机号码不能为空");
        if (StringUtils.isBlank(areaCode)) return RestResponse.failed("手机区号不能为空,手机区号:+86或者+853");
        try {
            logger.info("用户发送短信验证码:" + areaCode + "," + phone);
            if (StringUtils.isBlank(phone)) {
                logger.info("参数错误");
                return RestResponse.failed("参数错误");
            }
            //设置key 自动 +1
            long count = stringRedisTemplate.boundValueOps(SmsConstants.REDIS_SMS_USER_PREFIX + phone).increment(1);

            if (count == 1) {
                //设置 60 秒过期
                stringRedisTemplate.expire(SmsConstants.REDIS_SMS_USER_PREFIX + phone, SmsConstants.REDIS_SMS_USER_EXPIRE, TimeUnit.SECONDS);
            }
            if (count > 5) {
                logger.info("验证码发送频繁,超过了限定的次数");
                return RestResponse.failed("验证码发送频繁,超过了限定的次数");
            }
            //生成随机验证码
            String code = PhoneCodeUtil.getCode();
            //发送短信
            PhoneCodeUtil phoneCode = new PhoneCodeUtil();
            String sms = phoneCode.sendCode(phone, code, areaCode);
            //查看是否发送成功
            JSONObject json = JSONObject.fromObject(sms);
            String success = json.getString("Message");
            if (!success.equals("OK")) {
                //发送失败,次数减回来 -1 表示
                stringRedisTemplate.boundValueOps(SmsConstants.REDIS_SMS_USER_PREFIX + phone).increment(-1);
                return RestResponse.failed("短信发送失败");
                // return RestResponse.success("短信发送失败");
            }
            //发送成功,放入redis
            stringRedisTemplate.opsForValue().set(SmsConstants.REDIS_SMS_PREFIX + phone, code, SmsConstants.REDIS_SMS_EXPIRE, TimeUnit.SECONDS);

            logger.info("验证码发送成功");
            return RestResponse.success("操作成功:" + code);
        } catch (Exception e) {
            logger.info("短信验证码发送失败" + ExceptionUtils.getStackTrace(e));
            return RestResponse.failed("短信验证码发送失败");
        }
    }

    @ApiOperation(value = "检测手机验证码是否一致", notes = "检测手机验证码是否一致")
    @RequestMapping(value = "checkPhoneCode", method = RequestMethod.GET)
    public RestResponse checkPhoneCode(@RequestParam String phone,
                                       @RequestParam String code) {
        if (StringUtils.isBlank(phone)) return RestResponse.failed("手机号码不能为空!");
        if (StringUtils.isBlank(code)) return RestResponse.failed("验证码不能为空!");
        try {
            try {
                logger.info("开始验证手机号验证码:" + phone + "," + code);
                String rediscode = stringRedisTemplate.opsForValue().get(SmsConstants.REDIS_SMS_PREFIX + phone);

                if (rediscode == null || !rediscode.equals(code)) {
                    return RestResponse.failed("验证码错误");
                }
                logger.info("验证码验证成功");
                return RestResponse.success("验证码验证成功");
            } catch (Exception e) {
                logger.info("短信验证码验证失败" + ExceptionUtils.getStackTrace(e));
                return RestResponse.failed("短信验证码验证失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.success("验证成功");
    }


}

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Random;


public class PhoneCodeUtil {

    private static String AccessKeyID = "";
    private static String AccessKeySecret = "";
    private static String SignName = "";//签名
    private static String TemplateCode1 = "";//大陆模板
    private static String TemplateCode2 = "";//澳门模板

    /**
     * @param phone    发送到的手机号
     * @param code     验证码内容
     * @param areaCode 区号
     */
    public String sendCode(String phone, String code, String areaCode) {
        //此处放AccessKeyID和AccessKeySecret
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKeyID, AccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        //此处放接收验证码的手机号
        request.putQueryParameter("PhoneNumbers", phone);

        //此处放签名名称(必须审核通过)
        request.putQueryParameter("SignName", SignName);

        //此处放短信模板(必须审核通过)
        if (areaCode.equals("+86")) {
            request.putQueryParameter("TemplateCode", TemplateCode1); // 大陆
        }
        if (areaCode.equals("+853")) {
            request.putQueryParameter("TemplateCode", TemplateCode2); // 澳门
        }

        //此处放验证码的内容(JSON格式\"表示转义。JSON格式:{"code":"666666"})
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getData();

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 随机生成的6位验证码
     *
     * @return
     */
    public static String getCode() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; sb.length() < 6; i++) {
            int num = new Random().nextInt(10);
            sb.append(num);
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        PhoneCodeUtil phoneCode = new PhoneCodeUtil();
        // 获取随机验证码
        String code = phoneCode.getCode();
        // 接收短信的手机号
        String phone = "";
        String areaCode = "+86";
        // 调用发短信的方法
        phoneCode.sendCode(phone, code, areaCode);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值