首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現短信驗證碼與國際短信群發:基於雲片 API 完整示例

     編輯:Java 相關知識

前言

隨業務全球化拓展,短信驗證碼、國際短信群發成為標配需求。本文提供基於雲片(YunPian)短信平台的 Java 完整實現,涵蓋賬戶查詢、智能匹配模板發送、指定模板發送、語音驗證碼、主被叫綁定/解綁等核心接口,代碼開箱即用,並解析關鍵設計要點。

一、 核心依賴

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

基於 Apache HttpClient 4.3+ 實現 HTTP POST 請求,統一 UTF-8 編碼。

二、 完整工具類代碼

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;

public class JavaSmsApi {
    // 接口端點
    private static final String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";
    private static final String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";
    private static final String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
    private static final String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";
    private static final String URI_SEND_BIND = "https://call.yunpian.com/v2/call/bind.json";
    private static final String URI_SEND_UNBIND = "https://call.yunpian.com/v2/call/unbind.json";
    private static final String ENCODING = "UTF-8";

    /** 通用 POST 方法 */
    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (response != null) response.close(); } catch (Exception ignored) {}
        }
        return responseText;
    }

    // ========== 業務接口 ==========

    /** 查賬戶信息 */
    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        return post(URI_GET_USER_INFO, params);
    }

    /** 智能匹配模板發送(推薦) */
    public static String sendSms(String apikey, String text, String mobile) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        params.put("text", text);       // 內容需與已審核模板匹配
        params.put("mobile", mobile);
        return post(URI_SEND_SMS, params);
    }

    /** 指定模板發送 */
    public static String tplSendSms(String apikey, long tplId, String tplValue, String mobile) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tplId));
        params.put("tpl_value", tplValue); // URLEncoder 編碼後的鍵值對
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    /** 語音驗證碼 */
    public static String sendVoice(String apikey, String mobile, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        params.put("mobile", mobile);
        params.put("code", code);
        return post(URI_SEND_VOICE, params);
    }

    /** 綁定主被叫 */
    public static String bindCall(String apikey, String from, String to, Integer duration) {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        params.put("from", from);
        params.put("to", to);
        params.put("duration", String.valueOf(duration));
        return post(URI_SEND_BIND, params);
    }

    /** 解綁主被叫 */
    public static String unbindCall(String apikey, String from, String to) {
        Map<String, String> params = new HashMap<>();
        params.put("apikey", apikey);
        params.put("from", from);
        params.put("to", to);
        return post(URI_SEND_UNBIND, params);
    }

    // ========== 測試主方法 ==========
    public static void main(String[] args) throws Exception {
        String apikey = "xxxxxxxxxxxxxxxxxxxxx"; // 替換為你的 apikey
        String mobile = "130xxxxxxxx";           // 替換為目標手機號

        // 1. 查賬戶
        System.out.println("賬戶信息: " + getUserInfo(apikey));

        // 2. 智能匹配發送(推薦)
        String text = "【雲片網】您的驗證碼是1234";
        // System.out.println("智能發送: " + sendSms(apikey, text, mobile));

        // 3. 指定模板發送
        long tplId = 1; // 模板 ID
        String tplValue = URLEncoder.encode("#code#", ENCODING) + "=" + URLEncoder.encode("1234", ENCODING)
                        + "&" + URLEncoder.encode("#company#", ENCODING) + "=" + URLEncoder.encode("雲片網", ENCODING);
        System.out.println("模板變量: " + tplValue);
        System.out.println("模板發送: " + tplSendSms(apikey, tplId, tplValue, mobile));

        // 4. 語音驗證碼
        // System.out.println("語音驗證碼: " + sendVoice(apikey, mobile, "1234"));

        // 5. 綁定/解綁示例
        // String from = "+86130xxxxxxxx";
        // String to = "+86131xxxxxxxx";
        // System.out.println("綁定: " + bindCall(apikey, from, to, 30 * 60));
        // System.out.println("解綁: " + unbindCall(apikey, from, to));
    }
}

三、 關鍵設計要點解析

1. 智能匹配 vs 指定模板

  • 智能匹配:傳完整短信內容,平台自動匹配已審核模板,**推薦**,無需維護模板 ID,內容變更只需平台側更新模板。
  • 指定模板:傳 tpl_id + tpl_value,需自行 URLEncoder 編碼變量值,靈活但維護成本高。

2. 國際短信零代碼改造

雲片國際短信**複用相同接口**,只需:

  1. 在平台配置國際短信模板(支持西班牙、葡萄牙、意大利、港澳台等)。
  2. 手機號加國際區號(如 +346xxxxxxxx 西班牙)。
  3. 代碼**完全無需修改**,同一套邏輯覆蓋國內/國際。

3. 異常處理與重試策略(生產環境必加)

// 建議擴展:指數退避重試 + 熔斷 + 異步發送
public String sendWithRetry(String apikey, String text, String mobile, int maxRetry) {
    for (int i = 0; i < maxRetry; i++) {
        String resp = sendSms(apikey, text, mobile);
        if (isSuccess(resp)) return resp;
        sleep((long) Math.pow(2, i) * 100); // 100ms, 200ms, 400ms...
    }
    // 記錄失敗日志、進入補發隊列
    return "FAILED";
}

4. 安全與合規

  • apikey 嚴禁硬編碼:讀取配置中心/環境變量/密鑰管理系統。
  • 手機號脫敏日志:日志中僅保留前 3 後 4 位。
  • 頻率限制:單號碼/單 IP/單業務維度限流,防刷接口。
  • 內容合規:變量值長度、類型校驗,防注入非法內容。

四、 擴展:異步發送與監控

@Async("smsExecutor")
public CompletableFuture<String> sendAsync(String apikey, String text, String mobile) {
    return CompletableFuture.supplyAsync(() -> {
        try { return sendSms(apikey, text, mobile); }
        catch (IOException e) { throw new CompletionException(e); }
    });
}

// 監控指標:發送成功率、平均耗時、失敗碼分布、積壓隊列長度

五、 總結

基於雲片 API 的 Java 短信發送實現核心在於:

  1. 封裝通用 HTTP POST 工具方法,統一異常處理、資源釋放。
  2. 優先使用智能匹配模板,減少模板 ID 維護成本。
  3. 國際短信複用相同接口,零代碼改造擴展全球業務。
  4. 生產環境必須加上重試、熔斷、異步、監控、安全合規體系。

短信業務看似簡單,實則關係用戶體驗、安全合規與系統穩定。建議將發送邏輯封裝為獨立微服務/模組,統一接入網關、限流、審計,避免分散在各業務代碼中難以治理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved