public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
// 创建短信服务客户端并返回
// 创建一个配置对象
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId) // 设置访问密钥ID
.setAccessKeySecret(accessKeySecret); // 设置访问密钥
config.endpoint = "dysmsapi.aliyuncs.com"; // 设置服务终端地址
return new com.aliyun.dysmsapi20170525.Client(config); // 返回新的短信服务客户端对象
}
// 发送短信的方法
public boolean sendSms(String phone, String code) throws Exception {
code = "{\"code\":\"" + code + "\"}"; // 准备短信模板参数
// 创建短信服务客户端对象
com.aliyun.dysmsapi20170525.Client client = AliSmsUtils.createClient(accessKeyId, accessKeySecret);
// 创建发送短信请求对象并设置参数
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setPhoneNumbers(phone) // 设置手机号码
.setTemplateCode(templateCode) // 设置短信模板编码
.setTemplateParam(code) // 设置短信模板参数
.setSignName(signName); // 设置短信签名
try {
// 发送短信请求并获取响应
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
// 打印发送短信响应
System.out.println(sendSmsResponse);
} catch (TeaException error) {
// 处理可能发生的异常
System.out.println(error.getMessage());
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
// 返回true表示短信发送成功
return true;
}