javascript
Springboot接入华为云短信平台
? ? ? ? 最近公司的項目需要用到短信驗證碼,之前沒有做過短信的業務,就去華為云官網研究了一下,發現官網給出的教程相當完善,這邊記錄一下,希望大家能幫到大家。。。
? ? 一.華為云官網申請短信相關信息
1.1申請短信應用進入短信管理頁面-->應用管理,右上角-->添加應用,如下圖1
?然后按照官網要求填寫相關信息即可。
1.2申請短信簽名,進入短信管理頁面-->簽名管理,右上角-->添加簽名,按照要求完成填寫即可,注意:所有的申請都有審核時間,請耐心等待即可。
1.3申請短信模板,進入短信管理頁面-->模板管理,右上角-->添加模板,按照要求完成填寫即可,注意:申請的模板對內容有要求,申請時請仔細核對自己的申請內容,以免浪費不必要的時間。圖片就不放了,大家按照步驟申請就好。
二.代碼開發
2.1.完成上述雖有步驟,就開始引入華為云的短信接口,華為云官網有api的說明,鏈接如下短信api鏈接
?2.2,研讀一下API的說明,然后選擇代碼開發樣例,Java開發樣例,鏈接給出了已經寫好的樣例,各位只要發揮程序員的傳統藝能:Ctrl+C 復制,Ctrl+V粘貼,在自己的項目中創建好相應的類即可,代碼如下
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; //如果JDK版本是1.8,可使用原生Base64類 import java.util.Base64; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID;import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;//如果JDK版本低于1.8,請使用三方庫提供Base64類 //import org.apache.commons.codec.binary.Base64;public class SendSms {//無需修改,用于格式化鑒權頭域,給"X-WSSE"參數賦值private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";//無需修改,用于格式化鑒權頭域,給"Authorization"參數賦值private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";public static void main(String[] args) throws Exception {//必填,請參考"開發準備"獲取如下數據,替換為實際值String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1"; //APP接入地址(在控制臺"應用管理"頁面獲取)+接口訪問URIString appKey = "c8RWg3ggEcyd4D3p94bf3Y7x1Ile"; //APP_KeyString appSecret = "q4Ii87BhST9vcs8wvrzN80SfD7Al"; //APP_SecretString sender = "csms12345678"; //國內短信簽名通道號或國際/港澳臺短信通道號String templateId = "8ff55eac1d0b478ab3c06c3c6a492300"; //模板ID//條件必填,國內短信關注,當templateId指定的模板類型為通用模板時生效且必填,必須是已審核通過的,與模板類型一致的簽名名稱//國際/港澳臺短信不用關注該參數String signature = "華為云短信測試"; //簽名名稱//必填,全局號碼格式(包含國家碼),示例:+8615123456789,多個號碼之間用英文逗號分隔String receiver = "+86151****6789,+86152****7890"; //短信接收人號碼//選填,短信狀態報告接收地址,推薦使用域名,為空或者不填表示不接收狀態報告String statusCallBack = "";/*** 選填,使用無變量模板時請賦空值 String templateParas = "";* 單變量模板示例:模板內容為"您的驗證碼是${1}"時,templateParas可填寫為"[\"369751\"]"* 雙變量模板示例:模板內容為"您有${1}件快遞請到${2}領取"時,templateParas可填寫為"[\"3\",\"人民公園正門\"]"* 模板中的每個變量都必須賦值,且取值不能為空* 查看更多模板和變量規范:產品介紹>模板和變量規范*/String templateParas = "[\"369751\"]"; //模板變量,此處以單變量驗證碼短信為例,請客戶自行生成6位驗證碼,并定義為字符串類型,以杜絕首位0丟失的問題(例如:002569變成了2569)。//請求Body,不攜帶簽名名稱時,signature請填nullString body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);if (null == body || body.isEmpty()) {System.out.println("body is null.");return;}//請求Headers中的X-WSSE參數值String wsseHeader = buildWsseHeader(appKey, appSecret);if (null == wsseHeader || wsseHeader.isEmpty()) {System.out.println("wsse header is null.");return;}Writer out = null;BufferedReader in = null;StringBuffer result = new StringBuffer();HttpsURLConnection connection = null;InputStream is = null;HostnameVerifier hv = new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}};trustAllHttpsCertificates();try {URL realUrl = new URL(url);connection = (HttpsURLConnection) realUrl.openConnection();connection.setHostnameVerifier(hv);connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(true);//請求方法connection.setRequestMethod("POST");//請求Headers參數connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");connection.setRequestProperty("Authorization", AUTH_HEADER_VALUE);connection.setRequestProperty("X-WSSE", wsseHeader);connection.connect();out = new OutputStreamWriter(connection.getOutputStream());out.write(body); //發送請求Body參數out.flush();out.close();int status = connection.getResponseCode();if (200 == status) { //200is = connection.getInputStream();} else { //400/401is = connection.getErrorStream();}in = new BufferedReader(new InputStreamReader(is, "UTF-8"));String line = "";while ((line = in.readLine()) != null) {result.append(line);}System.out.println(result.toString()); //打印響應消息實體} catch (Exception e) {e.printStackTrace();} finally {try {if (null != out) {out.close();}if (null != is) {is.close();}if (null != in) {in.close();}} catch (Exception e) {e.printStackTrace();}}}/*** 構造請求Body體* @param sender* @param receiver* @param templateId* @param templateParas* @param statusCallBack* @param signature | 簽名名稱,使用國內短信通用模板時填寫* @return*/static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,String statusCallBack, String signature) {if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()|| templateId.isEmpty()) {System.out.println("buildRequestBody(): sender, receiver or templateId is null.");return null;}Map<String, String> map = new HashMap<String, String>();map.put("from", sender);map.put("to", receiver);map.put("templateId", templateId);if (null != templateParas && !templateParas.isEmpty()) {map.put("templateParas", templateParas);}if (null != statusCallBack && !statusCallBack.isEmpty()) {map.put("statusCallback", statusCallBack);}if (null != signature && !signature.isEmpty()) {map.put("signature", signature);}StringBuilder sb = new StringBuilder();String temp = "";for (String s : map.keySet()) {try {temp = URLEncoder.encode(map.get(s), "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}sb.append(s).append("=").append(temp).append("&");}return sb.deleteCharAt(sb.length()-1).toString();}/*** 構造X-WSSE參數值* @param appKey* @param appSecret* @return*/static String buildWsseHeader(String appKey, String appSecret) {if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {System.out.println("buildWsseHeader(): appKey or appSecret is null.");return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");String time = sdf.format(new Date()); //CreatedString nonce = UUID.randomUUID().toString().replace("-", ""); //NonceMessageDigest md;byte[] passwordDigest = null;try {md = MessageDigest.getInstance("SHA-256");md.update((nonce + time + appSecret).getBytes());passwordDigest = md.digest();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}//如果JDK版本是1.8,請加載原生Base64類,并使用如下代碼String passwordDigestBase64Str = Base64.getEncoder().encodeToString(passwordDigest); //PasswordDigest//如果JDK版本低于1.8,請加載三方庫提供Base64類,并使用如下代碼//String passwordDigestBase64Str = Base64.encodeBase64String(passwordDigest); //PasswordDigest//若passwordDigestBase64Str中包含換行符,請執行如下代碼進行修正//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);}/*** @throws Exception*/static void trustAllHttpsCertificates() throws Exception {TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {return;}public X509Certificate[] getAcceptedIssuers() {return null;}}};SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, null);HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());} }注意:按照代碼中注釋的要求,將url,appkey,appsecret,等相關字段,填寫成自己的就好了,注釋中有提到,相關字段的值,在上述申請的應用,簽名,以及模板中可以看到,替換即可。
2.3.所有的步驟都完成的話,就需要購買短信包,進行測試。注意:代碼示例給出的是一個main函數,AS能直接運行,
?,運行結果如下圖:
? ? 三.根據輸出結果來查找問題
3.1如上圖status為報錯的代碼:E200028,在華為錯誤碼頁面找到對應的錯誤原因,來查看自己修改代碼出現的問題,然后進行修改,錯誤API。
如上:我的運行結果為E200028,根據錯誤碼,原因為:模板變量校驗失敗;即模板中的變量和
templateParas中設置的變量不匹配,我的模板中設置了4個變量,而代碼中之有三個,所以報錯,修改完成如下: String templateParas ="[\"3361\",\"12345\",\"1124\",\"123456\"]"; 運行成功,手機接到設定的短信。遇到其他的問題可以通過錯誤碼查詢到相應的問題解決。四,修改代碼
4.1上面提到,華為提供的類中有一個main方法,無法被調用,所有最后講main方法修改為帶參數的方法即可。如下:
public static void sendSms(String code,String phone,String sender,String templateId) throws Exception然后就大功告成,在需要調用的地方調用sendSms方法即可。
至此,華為云短信平臺已經接入系統,剩下的就是根據需求來完成自己的業務了。
祝各位寫代碼愉快。
總結
以上是生活随笔為你收集整理的Springboot接入华为云短信平台的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【An electroencephalo
- 下一篇: 点阵字和字模