阿里云SDK中的凭证提供程序的创建
public String send(String phone) {
// Configure Credentials authentication information, including ak, secret, token
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
// Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
.accessKeyId(ALIBABA_CLOUD_ACCESS_KEY_ID)
.accessKeySecret(ALIBABA_CLOUD_ACCESS_KEY_SECRET)
//.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
.build());
// Configure the Client
AsyncClient client = AsyncClient.builder()
.region("cn-hangzhou") // Region ID
//.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
.credentialsProvider(provider)
//.serviceConfiguration(Configuration.create()) // Service-level configuration
// Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
.overrideConfiguration(
ClientOverrideConfiguration.create()
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
.setEndpointOverride("dysmsapi.aliyuncs.com")
//.setConnectTimeout(Duration.ofSeconds(30))
)
.build();
Sms sms = new Sms();
sms.setCode(getFourRandom());
// 存redis,5分钟有效期
stringRedisTemplate.opsForValue().set(phone,sms.getCode(),500, TimeUnit.SECONDS);
SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
.phoneNumbers(phone)
.signName(signName)
.templateCode(templateCode)
.templateParam(JSONObject.toJSONString(sms))
// Request-level configuration rewrite, can set Http request parameters, etc.
// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
.build();
// Asynchronously get the return value of the API request
CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
// Synchronously get the return value of the API request
SendSmsResponse resp = null;
try {
resp = response.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(new Gson().toJson(resp));
// Finally, close the client
client.close();
return new Gson().toJson(resp);
}
@ApiOperation("手机验证码获取")
@GetMapping("getSms")
public Result<String> getSms(@RequestParam(required = true) @ApiParam("手机号码") String phone) {
JSONObject jsonObject = JSONObject.parseObject(smsUtil.send(phone));
String body = jsonObject.getString("body");
JSONObject bodyObject = JSONObject.parseObject(body);
String code = bodyObject.getString("code");
if(code.equals("OK")) {
return Result.OK("验证码发送成功,有效期为5分钟!");
}else {
return Result.error("发送失败,请重试!");
}
}