关于华为云短信接口对接问题
生活随笔
收集整理的這篇文章主要介紹了
关于华为云短信接口对接问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
華為云---消息&短信
- 對(duì)接API
- 問(wèn)題
對(duì)接API
華為云基礎(chǔ)示例
https://support.huaweicloud.com/devg-msgsms/sms_04_0002.html
自定義項(xiàng)目工具類
package com.china.xxx;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.NoopHostnameVerifier; 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.beans.factory.annotation.Value; import org.springframework.stereotype.Service;import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.*;public class HuaweiMessageApi {//無(wú)需修改,用于格式化鑒權(quán)頭域,給"X-WSSE"參數(shù)賦值private final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";//無(wú)需修改,用于格式化鑒權(quán)頭域,給"Authorization"參數(shù)賦值private final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";@Value("${huaweiSms.url}")private String url; //APP接入地址+接口訪問(wèn)URI@Value("${huaweiSms.appKey}")private String appKey; //APP_Key@Value("${huaweiSms.appSecret}")private String appSecret; //APP_Secret@Value("${huaweiSms.sender}")private String sender; //國(guó)內(nèi)短信簽名通道號(hào)或國(guó)際/港澳臺(tái)短信通道號(hào)@Value("${huaweiSms.signature}")private String signature; //簽名名稱public void sendMessage(String templateId, String receiver, String templateParas){//receiver = "18500851993"; //短信接收人號(hào)碼String statusCallBack = "";/*** 選填,使用無(wú)變量模板時(shí)請(qǐng)賦空值 String templateParas = "";* 單變量模板示例:模板內(nèi)容為"您的驗(yàn)證碼是${1}"時(shí),templateParas可填寫為"[\"369751\"]"* 雙變量模板示例:模板內(nèi)容為"您有${1}件快遞請(qǐng)到${2}領(lǐng)取"時(shí),templateParas可填寫為"[\"3\",\"人民公園正門\"]"* 模板中的每個(gè)變量都必須賦值,且取值不能為空* 查看更多模板和變量規(guī)范:產(chǎn)品介紹>模板和變量規(guī)范*///String templateParas = "[\"" + content + "\"]";//請(qǐng)求Body,不攜帶簽名名稱時(shí),signature請(qǐng)?zhí)頽ullString body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature);if (null == body || body.isEmpty()) {System.out.println("body is null.");return;}//請(qǐng)求Headers中的X-WSSE參數(shù)值String wsseHeader = buildWsseHeader(appKey, appSecret);if (null == wsseHeader || wsseHeader.isEmpty()) {System.out.println("wsse header is null.");return;}try {//如果JDK版本是1.8,可使用如下代碼//為防止因HTTPS證書認(rèn)證失敗造成API調(diào)用失敗,需要先忽略證書信任問(wèn)題CloseableHttpClient client = HttpClients.custom().setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,(x509CertChain, authType) -> true).build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();HttpResponse response = client.execute(RequestBuilder.create("POST")//請(qǐng)求方法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()); //打印響應(yīng)頭域信息System.out.println(EntityUtils.toString(response.getEntity())); //打印響應(yīng)消息實(shí)體} catch (Exception e) {e.printStackTrace();}}/*** 構(gòu)造請(qǐng)求Body體** @param sender* @param receiver* @param templateId* @param templateParas* @param statusCallbackUrl* @param signature | 簽名名稱,使用國(guó)內(nèi)短信通用模板時(shí)填寫* @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"));}/*** 構(gòu)造X-WSSE參數(shù)值** @param appKey* @param appSecret* @return*/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,請(qǐng)加載原生Base64類,并使用如下代碼String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest//若passwordDigestBase64Str中包含換行符,請(qǐng)執(zhí)行如下代碼進(jìn)行修正//passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);} }問(wèn)題
小編發(fā)現(xiàn)問(wèn)題,就是所有短信必須帶有標(biāo)簽,如果沒(méi)有標(biāo)簽是不允許發(fā)送
總結(jié)
以上是生活随笔為你收集整理的关于华为云短信接口对接问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 武汉电博会看点 daydao电商云ERP
- 下一篇: 经验分享——关于大学生科研那些事