作者:思恋相依相惜 | 来源:互联网 | 2023-08-29 16:14
话不多说,直接上。(底下会给代码文本)第一步pom依赖第二步写工具类packagecb.cloud.trade.core.utils;importcom.aliyu
话不多说,直接上。(底下会给代码文本)
第一步 pom依赖
第二步 写工具类
package cb.cloud.trade.core.utils;import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;/*** @author tom* @create 2021/11/5 1:38 下午* 阿里短信发送Util*/
@Slf4j
public class AliSendSmsUtil {private static String accessKeyId = "xxxxxxxxxx";private static String accessKeySecret = "xxxxxxxxxx";private static String FROM = "xxxxxxxxxx";/*** 更换手机号验证码模板*/private static String REPLACE_MOBILE_ID = "xxxxxxxxxx";/*** 汇款验证码模板*/private static String REMITTANCE_CODE_ID = "xxxxxxxxxx";public static String SEND_SMS_TYPE_REPLACE_MOBILE = "发短信场景:更换手机号";public static String SEND_SMS_TYPE_REMITTANCE = "发短信场景:汇款";public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {Config config = new Config();config.accessKeyId = accessKeyId;config.accessKeySecret = accessKeySecret;return new Client(config);}public static String sendSms(String type, String mobile, String smsCode) {try {Client client = AliSendSmsUtil.createClient(accessKeyId, accessKeySecret);SendSmsRequest sendSmsRequest = new SendSmsRequest();sendSmsRequest.setPhoneNumbers(mobile);sendSmsRequest.setSignName(FROM);if (type.equalsIgnoreCase(SEND_SMS_TYPE_REPLACE_MOBILE)) {sendSmsRequest.setTemplateCode(REPLACE_MOBILE_ID);} else {sendSmsRequest.setTemplateCode(REMITTANCE_CODE_ID);}sendSmsRequest.setTemplateParam("{\"code\":\"" + smsCode + "\"}");SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);if (null != sendSmsResponse && null != sendSmsResponse.getBody() && sendSmsResponse.getBody().code.equals("OK")) {return smsCode;}} catch (Exception e) {log.error("阿里发送短信错误:{}", e);//返回8个8 方便后续发现用户收不到短信 看日志 可以快速查到日志位置return "88888888";}return smsCode;}
}