调用腾讯API发短信

1、导入pom依赖:

<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
<!-- 请到https://search.maven.org/search?q=tencentcloud-sdk-java查询最新版本 -->
<version>3.0.112</version>
</dependency>

2、代码
public static String sendSMS(){
        String result = "";
        // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,见《创建secretId和secretKey》小节
        Credential cred = new Credential("XXX",
                "XXX");

        // 实例化要请求产品(以cvm为例)的client对象
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);
        SmsClient smsClient = new SmsClient(cred, "ap-chongqing");//第二个ap-chongqing 填产品所在的区
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppid("1111");//appId ,见《创建应用》小节
        String[] phones={"+8613822222222"};  //发送短信的目标手机号,可填多个。
        sendSmsRequest.setPhoneNumberSet(phones);
        sendSmsRequest.setTemplateID("333333");  //模版id,见《创建短信签名和模版》小节
        String [] templateParam={getCode()};//模版参数,从前往后对应的是模版的{1}、{2}等,见《创建短信签名和模版》小节
        sendSmsRequest.setTemplateParamSet(templateParam);
        sendSmsRequest.setSign("哈哈哈"); //签名内容,不是填签名id,见《创建短信签名和模版》小节
        try {
            SendSmsResponse sendSmsResponse= smsClient.SendSms(sendSmsRequest); //发送短信
            SendStatus[] status = sendSmsResponse.getSendStatusSet();
            for (SendStatus st : status) {
                if(st.getCode().equalsIgnoreCase("Ok")){
                    result = st.getCode();
                } else {
                    result = st.getMessage();
                }
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return result;
    }

 



posted @ 2022-07-12 15:25  Caesar_the_great  阅读(241)  评论(0编辑  收藏  举报