springboot2.x 接入阿裡雲市場短信發送的實現

1.短信平臺購買次數地址

https://market.aliyun.com/products/57000002/cmapi00046920.html

提供測試模板、免審核、測試成本更低

2.測試學習使用的話,3塊錢75多次夠用瞭

3.購買後在跳轉成功頁面記錄

AppSecret、key、code

 4.記錄模板ID

5.上代碼環節

@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
        return new RestTemplate(requestFactory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory  = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(10000);
        factory.setConnectTimeout(10000);
        return factory;
    }
 
}

增加配置

@ConfigurationProperties(prefix = "sms")
@Configuration
@Data
public class SmsConfig {
 
    private String templateId;
 
    private String appCode;
 
}

application.yml

發送類

@Component
@Slf4j
public class SmsComponent {
 
    /**
     * 發送地址
     */
    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";
 
    @Autowired
    private RestTemplate restTemplate;
 
    @Autowired
    private SmsConfig smsConfig;
 
 
    /**
     * 發送短信驗證碼
     * @param to
     * @param templateId
     * @param value
     */
    public void send(String to,String templateId,String value){
 
        String url = String.format(URL_TEMPLATE,to,templateId,value);
        HttpHeaders headers = new HttpHeaders();
     
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("url={},body={}",url,response.getBody());
        if(response.getStatusCode().is2xxSuccessful()){
            log.info("發送短信驗證碼成功");
        }else {
            log.error("發送短信驗證碼失敗:{}",response.getBody());
        }
 
    }
}

測試類驗證

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AccountApplication.class)
@Slf4j
public class SmsTest { 
    @Autowired
    private SmsComponent smsComponent;
 
    @Autowired
    private SmsConfig smsConfig;
 
    @Test
    public  void testSendSms(){
 
        smsComponent.send("138XXXXXXX",smsConfig.getTemplateId(),"666888");
    }
}

發送成功咯

到此這篇關於springboot2.x 接入阿裡雲市場短信發送的實現的文章就介紹到這瞭,更多相關springboot 阿裡雲短信發送內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: