1.導包
<!-- 騰訊短信/tencentcloud-sdk-java --> <dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>tencentcloud-sdk-java</artifactId> <version>3.1.270</version> <!--<version>4.0.11</version>--> </dependency>
2.工具類
package com.dlb.utils; import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.exception.TencentCloudSDKException; //導入可選配置類 import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.HttpProfile; // 導入對應SMS模塊的client import com.tencentcloudapi.sms.v20210111.SmsClient; // 導入要請求接口對應的request response類 import com.tencentcloudapi.sms.v20210111.models.*; import lombok.Data; import java.util.Random; //騰訊短信 @Data @SuppressWarnings("all") public class TencentMsg { //秘鑰 private static String secretId="XXXXXXXXXXX"; private static String secretKey="XXXXXXXX"; /* 短信應用ID: 短信SdkAppId在 [應用管理列表] */ private static String sdkAppId = "1400XXXXX"; /* 短信簽名內容 必須填寫已審核通過的簽名 */ private static String signName = "XXX網"; /* 國際/港澳台短信 SenderId: 國內短信填空,默認未開通 */ private static String senderid = ""; /* 短信號碼擴展號: 默認未開通,如需開通請聯系 [sms helper] */ private static String extendCode = ""; /** * 1232XXX 普通短信 * 大蘿卜 * 您正在申請手機注冊,驗證碼為:{1},{2}分鍾內有效! * 已通過 2021-12-09 10:25:18 * 1232XXX 普通短信 * 大蘿卜 * 您正在修改注冊手機號碼,驗證碼為:{1},5分鍾有效,為保障帳戶安全,請勿向任何人提供此驗證碼。 * 已通過 2021-12-09 09:40:33 * 1232XXX 普通短信 * 大蘿卜 * 驗證碼為:{1},您正在登錄,若非本人操作,請勿泄露。 */ private static String templateId = "1232XXX"; //初始化短信發送客戶端 public static SmsClient initClient(){ //必要步驟: Credential cred = new Credential(secretId, secretKey); // 實例化一個http選項,可選,沒有特殊需求可以跳過 HttpProfile httpProfile = new HttpProfile(); // 設置代理 // httpProfile.setProxyHost("真實代理ip"); // httpProfile.setProxyPort(真實代理端口); /* SDK默認使用POST方法。 * 如果你一定要使用GET方法,可以在這里設置。GET方法無法處理一些較大的請求 */ httpProfile.setReqMethod("POST"); /* SDK有默認的超時時間,非必要請不要進行調整*/ httpProfile.setConnTimeout(60); /* SDK會自動指定域名。通常是不需要特地指定域名的,但是如果你訪問的是金融區的服務 * 則必須手動指定域名,例如sms的上海金融區域名: sms.ap-shanghai-fsi.tencentcloudapi.com */ httpProfile.setEndpoint("sms.tencentcloudapi.com"); /* 非必要步驟: * 實例化一個客戶端配置對象,可以指定超時時間等配置 */ ClientProfile clientProfile = new ClientProfile(); /* SDK默認用TC3-HMAC-SHA256進行簽名 * 非必要請不要修改這個字段 */ clientProfile.setSignMethod("HmacSHA256"); clientProfile.setHttpProfile(httpProfile); /* 實例化要請求產品(以sms為例)的client對象 * 第二個參數是地域信息,可以直接填寫字符串ap-guangzhou,或者引用預設的常量 */ return new SmsClient(cred, "ap-guangzhou",clientProfile); } //使用短信登錄 public String sendLogin(String msgCode,String phoneNumber,String userInfo){ SmsClient client = initClient(); // 實例化一個請求對象 SendSmsRequest req = new SendSmsRequest(); //------組裝短信內容 req.setSmsSdkAppId(sdkAppId);//應用id req.setSignName(signName);//網站簽名 req.setSenderId(senderid);//國外短信 req.setSessionContext(userInfo);//請求信息自定義,也可以為"xxx" req.setExtendCode(extendCode);//擴展號碼 req.setTemplateId(templateId);//申請的模板id String[] arr = {phoneNumber}; req.setPhoneNumberSet(arr);//手機號,最大200個 String[] code = {msgCode}; req.setTemplateParamSet(code);//模板里的變量,按數組順序放入 try { //發送短信 SendSmsResponse res = client.SendSms(req); //通過官網接口文檔或跳轉到response對象的定義處查看返回字段的定義 System.out.println(res.getRequestId()); //發送成功返回發送信息 return SendSmsResponse.toJsonString(res); } catch (TencentCloudSDKException e) { e.printStackTrace(); } return null; } public String getMsgCode(){ Random random = new Random(); String a= ""; int j = random.nextInt(9); for (int i = 0; i < 6; i++) { a += String.valueOf(random.nextInt(9)); } return a; } /** * 開放式發送短信 * @param verifyInfo 模板里的變量: 驗證碼:code必須是數字類型的字符串 時間5分鍾 * String[] templateParamSet = {"code","5"}; * @param phoneNumberSet 手機號 前面要寫+86 國內用 * String[] phoneNumberSet = {"+8617639563050"}; * @param sessionContext * 用戶的 session 內容: 不寫就用xxx代替,server 會原樣返回 * @return 返回的 res 是一個 SendSmsResponse 類的實例,與請求對象對應 * {"SendStatusSet":[ * {"SerialNo":"2640:246877675516390197684686305", * "PhoneNumber":"+861763956xxxx", * "Fee":1, * "SessionContext":"xxx", * "Code":"Ok", * "Message":"send success", * "IsoCode":"CN"} * ], * "RequestId":"d240c44b-a2e5-45ef-b3b5-00f23ac42b5f"} * * d240c44b-a2e5-45ef-b3b5-00f23ac42b5f */ public String sendMsg(String[] verifyInfo,String[] phoneNumberSet,String sessionContext){ SmsClient client = initClient(); // 實例化一個請求對象 SendSmsRequest req = new SendSmsRequest(); //------組裝短信內容 req.setSmsSdkAppId(sdkAppId);//應用id req.setSignName(signName);//網站簽名 req.setSenderId(senderid);//國外短信 req.setSessionContext(sessionContext);//請求信息自定義,也可以為"xxx" req.setExtendCode(extendCode);//擴展號碼 req.setTemplateId(templateId);//申請的模板id req.setPhoneNumberSet(phoneNumberSet);//手機號,最大200個 req.setTemplateParamSet(verifyInfo);//模板里的變量,按數組順序放入 try { //發送短信 SendSmsResponse res = client.SendSms(req); //通過官網接口文檔或跳轉到response對象的定義處查看返回字段的定義 System.out.println(res.getRequestId()); //發送成功返回發送信息 return SendSmsResponse.toJsonString(res); } catch (TencentCloudSDKException e) { e.printStackTrace(); } return null; } /** * 獲取回執狀態 * @param limit 設置拉取最大條數,最多100條 Long類型 5L * @return {"PullSmsSendStatusSet":[],"RequestId":"65d63875-b902-45c2-81be-810f01ea0ee3"} */ public String getReceipt(Long limit){ SmsClient client = initClient(); /* 實例化一個請求對象,根據調用的接口和實際情況,可以進一步設置請求參數*/ PullSmsSendStatusRequest req = new PullSmsSendStatusRequest(); req.setSmsSdkAppId(sdkAppId);//應用id req.setLimit(limit); /* 通過 client 對象調用 PullSmsSendStatus 方法發起請求。注意請求方法名與請求對象是對應的 * 返回的 res 是一個 PullSmsSendStatusResponse 類的實例,與請求對象對應 */ try { PullSmsSendStatusResponse res = client.PullSmsSendStatus(req); String s = PullSmsSendStatusResponse.toJsonString(res); // 輸出json格式的字符串回包 System.out.println(s); return s; } catch (TencentCloudSDKException e) { e.printStackTrace(); } return null; } /** * 統計短信發送數據 * @return {"SendStatusStatistics":{ * "FeeCount":1,"RequestCount":1,"RequestSuccessCount":1}, * "RequestId":"b5f388f0-bdf3-4c8c-8cc7-be8ca8bdda3f"} */ public String statisticalSendData(){ SmsClient client = initClient(); /* 實例化一個請求對象,根據調用的接口和實際情況,可以進一步設置請求參數*/ SendStatusStatisticsRequest req = new SendStatusStatisticsRequest(); req.setSmsSdkAppId(sdkAppId); // 設置拉取最大條數,最多100條 Long limit = 5L; req.setLimit(limit); /* 偏移量 注:目前固定設置為0 */ Long offset = 0L; req.setOffset(offset); /* 開始時間,yyyymmddhh 需要拉取的起始時間,精確到小時 */ String beginTime = "2021120908"; req.setBeginTime(beginTime); /* 結束時間,yyyymmddhh 需要拉取的截止時間,精確到小時 * 注:EndTime 必須大於 beginTime */ String endTime = "2021120912"; req.setEndTime(endTime); /* 通過 client 對象調用 SendStatusStatistics 方法發起請求。注意請求方法名與請求對象是對應的 * 返回的 res 是一個 SendStatusStatisticsResponse 類的實例,與請求對象對應 */ try { SendStatusStatisticsResponse res = client.SendStatusStatistics(req); String s = SendStatusStatisticsResponse.toJsonString(res); // 輸出json格式的字符串回包 System.out.println(s); return s; } catch (TencentCloudSDKException e) { e.printStackTrace(); } return null; } /** * //申請模板,需要企業認證類型賬號!!! * @param templatename String templatename = "阿里雲"; * @param templatecontent 模板內容 "{1}為您的登錄驗證碼,請於{2}分鍾內填寫"; * @param smstype 短信類型:0表示普通短信, 1表示營銷短信 建議:0 * @param international 是否國際/港澳台短信:0:表示國內短信,1:表示國際/港澳台短信。建議:0 * @param remark 模板備注:例如申請原因,使用場景等 "xxx" * @return json */ public static String a(String templatename, String templatecontent, long smstype, long international, String remark){ SmsClient client = initClient(); /* 實例化一個請求對象,根據調用的接口和實際情況,可以進一步設置請求參數*/ AddSmsTemplateRequest req = new AddSmsTemplateRequest(); req.setTemplateName(templatename); req.setTemplateContent(templatecontent); req.setSmsType(smstype); req.setInternational(international); req.setRemark(remark); try { AddSmsTemplateResponse res = client.AddSmsTemplate(req); // 可以取出單個值,您可以通過官網接口文檔或跳轉到 response 對象的定義處查看返回字段的定義 System.out.println(res.getRequestId()); String s = AddSmsTemplateResponse.toJsonString(res); // 輸出 JSON 格式的字符串回包 System.out.println(s); return s; } catch (TencentCloudSDKException e) { e.printStackTrace(); } return null; } }
3.服務調用
//獲取手機驗證碼 @RequestMapping("/getCode") @ResponseBody public String getPhoneCode(String phone,HttpServletRequest request){ if (phone == null) return ""; System.err.println("用戶輸入:"+phone); HttpSession session = request.getSession(); TencentMsg tencentMsg = new TencentMsg(); String msgCode = tencentMsg.getMsgCode();//獲取隨機驗證碼 System.err.println("msgCode = " + msgCode); JSONObject jsonObject = new JSONObject(); jsonObject.put("msgCode",msgCode);//存驗證碼 jsonObject.put("createTime",System.currentTimeMillis());//存當前時間 session.setAttribute("verifyInfo",jsonObject); String aaa = tencentMsg.sendLogin(msgCode, phone, "aaa"); System.out.println("aaa = " + aaa); return aaa; } //驗證手機驗證碼 @RequestMapping("/regAccount") @ResponseBody public String regAccount(String phone,String phoneCode,HttpServletRequest request){ HttpSession session = request.getSession(); JSONObject json = (JSONObject) session.getAttribute("verifyInfo"); if (!json.getString("msgCode").equals(phoneCode)){ return "驗證碼錯誤"; } if ((System.currentTimeMillis()-json.getLong("createTime"))>5*60*1000){ return "驗證碼過期"; } return "ok"; }