【親測可用】阿里雲簡訊

刘贵庆發表於2024-10-18

   <!--阿里雲-簡訊-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!--阿里雲-簡訊-->

  

package org.example;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;

import java.util.Objects;

/**
 * 阿里雲簡訊
 */
public class aliyunSMS {


    /**
     * 阿里雲 簡訊 初始化Client
     */
    public static Client newClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args) throws Exception {
        //第一步:在https://dysms.console.aliyun.com/domestic/text中生成簽名、模板並稽核透過,
        //第二步:加入引數傳送簡訊:
        //name key忘記,請在:【頭像】-->【AccessKey管理】重新加入生成一個
        String smsAccessKeyId = "";//name
        String smsAccessKeySecret = "";//key
        String smsEndpoint = "dysmsapi.aliyuncs.com";//阿里雲簡訊域名  固定不變
        String smsSignName = "";//簽名名稱
        String smsTemplateCode = "";//簽名的模板CODE
        String phones = "";//手機號碼
        String phonecode = "";//動態碼


        Client client = newClient(smsAccessKeyId, smsAccessKeySecret, smsEndpoint);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(smsSignName)
                .setTemplateCode(smsTemplateCode)
                .setPhoneNumbers(phones)
                .setTemplateParam("{\"code\":\"" + phonecode + "\"}");
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (Objects.nonNull(sendSmsResponse) && sendSmsResponse.getBody().code.equals("OK")) {
                System.out.println("簡訊傳送成功。");
            }
        } catch (TeaException error) {
            System.out.println("阿里雲簡訊傳送異常: " + error.message);
        }
    }


}

  

相關文章