JAVA阿里云发送短信验证码代码


有几个特别的注意部分:
修改IDE的Editor字符编码为UTF-8,阿里云模板签名保存在Properties,可能要包含中文,防止乱码,与服务器签署 的签名不匹配.
发送JSON格式问题,最终发送的验证码,需要在程序中拼接好双引号,setTemplateParam("{\"code\":\"" + code + "\"}");
多余字符会引起 返回JSON参数异常

//导包部分
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

//方法部分

/**
* 向用户手机发送验证码 * * @param mobile 传入的手机号 * @return 发送成功, 返回"OK",失败null */ public String sendSms(String mobile) { String code = RandomUtil.randomNumbers(6); System.out.println("code = " + code); try { //Construct the Config By AccessKey,KeySecret,Ali_SMS_URL Config config = new Config() .setAccessKeyId(this.aliyunSMSConfig.getAccessKeyId()) .setAccessKeySecret(this.aliyunSMSConfig.getAccessKeySecret()) .setEndpoint(this.aliyunSMSConfig.getDomain()); //构造Client ,需要配置传入 Client client = new Client(config); SendSmsRequest sendSmsRequest = new SendSmsRequest() .setPhoneNumbers(mobile) .setSignName(this.aliyunSMSConfig.getSignName()) .setTemplateCode(this.aliyunSMSConfig.getTemplateCode()) //模板支持的格式 是 {"key":"value"} ,所以还需要拼接双引号,而且不能有多余无效字符,
            //不然 返回值会报JSON参数不合法
.setTemplateParam("{\"code\":\"" + code + "\"}"); // client发送方法中 传入一个 "发送请求对象" SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest); SendSmsResponseBody body = sendSmsResponse.getBody(); System.out.println("body = " + body.getCode()); if (StrUtil.equals("OK", body.getCode())) { return code; } } catch (Exception e) { log.error("验证码发送失败, 手机号:" + mobile + "\n", e); } return null; // return code; }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM