當前位置:
                    首頁 >
                            前端技术
>                            javascript
>内容正文                
                        
                    javascript
SpringBoot下实现华为云短信验证功能(含代码)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                SpringBoot下实现华为云短信验证功能(含代码)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                準備工作
(確定添加等待審核即可,審核需要兩個小時左右)
復制修改適合自己的項目需求即可,如下是我的修改樣例
樣例
package com.lm.cloud.backstage.controller;//如果JDK版本低于1.8,請使用三方庫提供Base64類 //import org.apache.commons.codec.binary.Base64;import com.lm.cloud.constant.JwtConstant; import com.lm.cloud.utils.RedisUtil; import com.lm.cloud.vo.QueryCustomerVo; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.*; //如果JDK版本是1.8,可使用原生Base64類@RequestMapping("/sms") public class SendSmsController {//無需修改,用于格式化鑒權頭域,給"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\"";@PostMapping("/sendSms")public static void sendSms(@RequestBody QueryCustomerVo customerVo) throws Exception {//必填,請參考"開發準備"獲取如下數據,替換為實際值String url = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1"; //APP接入地址+接口訪問URIString appKey = JwtConstant.APP_KEY; //應用管理中的 APP_Key String appSecret = JwtConstant.APP_SECRET; //應用管理中的APP_SecretString sender = JwtConstant.APP_SENDER; //簽名管理中的國內短信簽名通道號或國際/港澳臺短信通道號String templateId = JwtConstant.APP_TEMPLATE_ID; //模板管理中的模板ID//條件必填,國內短信關注,當templateId指定的模板類型為通用模板時生效且必填,必須是已審核通過的,與模板類型一致的簽名名稱//國際/港澳臺短信不用關注該參數String signature = "華為云短信驗證碼"; //簽名名稱//必填,全局號碼格式(包含國家碼),示例:+8615123456789,多個號碼之間用英文逗號分隔String receiver = customerVo.getContactPhone(); //短信接收人號碼//選填,短信狀態報告接收地址,推薦使用域名,為空或者不填表示不接收狀態報告String statusCallBack = "";/*** 選填,使用無變量模板時請賦空值 String templateParas = "";* 單變量模板示例:模板內容為"您的驗證碼是${1}"時,templateParas可填寫為"[\"369751\"]"* 雙變量模板示例:模板內容為"您有${1}件快遞請到${2}領取"時,templateParas可填寫為"[\"3\",\"人民公園正門\"]"* 模板中的每個變量都必須賦值,且取值不能為空* 查看更多模板和變量規范:產品介紹>模板和變量規范*//*** 隨機生成六位數的驗證碼代碼樣例*/String code = "";Random random = new Random();for (int i = 0; i < 6; i++) {int r = random.nextInt(10); //每次隨機出一個數字(0-9)code = code + r; //把每次隨機出的數字拼在一起}String templateParas = "[\"" + code + "\"]"; //模板變量,此處以單變量驗證碼短信為例,請客戶自行生成6位驗證碼,并定義為字符串類型,以杜絕首位0丟失的問題(例如:002569變成了2569)。//刪除redis中該手機的驗證碼RedisUtil.del(receiver);//將生成的驗證碼存到redis中,5分鐘有效RedisUtil.setExpire(receiver, code, 60 * 5);//請求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;}//如果JDK版本是1.8,可使用如下代碼CloseableHttpClient client = HttpClients.custom().setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,(x509CertChain, authType) -> true).build()).setSSLHostnameVerifier(new DefaultHostnameVerifier()).build();HttpResponse response = client.execute(RequestBuilder.create("POST")//請求方法POST.setUri(url).addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded").addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE).addHeader("X-WSSE", wsseHeader).setEntity(new StringEntity(body)).build());System.out.println(response.toString()); //打印響應頭域信息System.out.println(EntityUtils.toString(response.getEntity())); //打印響應消息實體}/*** 構造請求Body體** @param sender* @param receiver* @param templateId* @param templateParas* @param statusCallbackUrl* @param signature | 簽名名稱,使用國內短信通用模板時填寫* @return*/static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,String statusCallbackUrl, 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;}List<NameValuePair> keyValues = new ArrayList<NameValuePair>();keyValues.add(new BasicNameValuePair("from", sender));keyValues.add(new BasicNameValuePair("to", receiver));keyValues.add(new BasicNameValuePair("templateId", templateId));if (null != templateParas && !templateParas.isEmpty()) {keyValues.add(new BasicNameValuePair("templateParas", templateParas));}if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));}if (null != signature && !signature.isEmpty()) {keyValues.add(new BasicNameValuePair("signature", signature));}return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));}/*** 構造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("-", ""); //Noncebyte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);String hexDigest = Hex.encodeHexString(passwordDigest);//如果JDK版本是1.8,請加載原生Base64類,并使用如下代碼String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest//如果JDK版本低于1.8,請加載三方庫提供Base64類,并使用如下代碼//String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest//若passwordDigestBase64Str中包含換行符,請執行如下代碼進行修正//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);} }(注:上述app_key等被封裝引用)
/*** 華為云短信驗證 APP_Key 為保隱私,皆用*代替*/public static final String APP_KEY = "***************";/*** 華為云短信驗證 APP_Secret*/public static final String APP_SECRET = "***************";/*** 華為云短信驗證 國內短信簽名通道號*/public static final String APP_SENDER = "***************";/*** 華為云短信驗證 模板ID*/public static final String APP_TEMPLATE_ID = "***************";postman測試
 
總結
以上是生活随笔為你收集整理的SpringBoot下实现华为云短信验证功能(含代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: h5图形化工具
- 下一篇: CentOS6.5安装Chromium谷
