有幾個特別的注意部分:
修改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;
}