阿里云 - 短信服務

阿里的文件寫得很清楚了: https://help.aliyun.com/document\_detail/59210.html?spm=a2c4g.11174283.4.1.8d482c421n0wbN

重點就是要申請 keyId, keySecret,還要申請"簽名"、"文字模板" (因為中國什麼都要審核啦)

都申請完後可以下載 DEMO 來試試看發簡訊,只要將上述那些參數置換成自己的參數,應該就可以發成功了

寫在自己 server 上的話,先在 pom.xml 裡加上 maven dependency

<!--  Ali SMS -->
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.6</version> <!-- 注:如提示报错,先升级基础包版,无法解决可联系技术支持 -->
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  <version>1.1.0</version>
</dependency>

接者設計一下 API,短信驗證需要兩個 API,一個是送簡訊,一個是將驗證碼送給 server 做驗證,

@RequestMapping(value = "/getVerificationSMS", method = RequestMethod.POST)
public JsonResponse getVerificationSMS(@PathVariable final Long siteId, @RequestBody final ReqSmsVO smsVO) throws AppException, JsonProcessingException, IOException, ClientException {
    String code = this.miniProgramService.getVerificationSMS(siteId, smsVO);
    if (!code.isEmpty())
        return JsonResponse.ok().withData(code);
    return JsonResponse.failed();
}

@RequestMapping(value = "/sendVerificationCode", method = RequestMethod.POST)
public JsonResponse sendVerificationCode(@PathVariable final Long siteId, @RequestBody final ReqSmsVO smsVO) throws AppException, JsonProcessingException, IOException, ClientException {
    Boolean result = this.miniProgramService.sendSMSVerification(siteId, smsVO);
    if (result)
        return JsonResponse.ok().withData(result);
    return JsonResponse.failed().withData(result);
}

裡面的邏輯就不贅述, getVerificationSMS 就是把阿里的 DEMO 貼一貼即可,產生 verification code 的話,可以用簡單的小函式去產生驗證碼:

private static String getVerificationCode(final Map<String, String> verificationCodeMap, final String phoneNumber) {
    int count = 6;
    final String NUMERIC_STRING = "0123456789";
    StringBuilder builder = new StringBuilder();

    while (count-- != 0) {
        int character = (int) (Math.random() * NUMERIC_STRING.length());
        builder.append(NUMERIC_STRING.charAt(character));
    }
    logger.debug("verification code is: " + builder.toString());
    verificationCodeMap.put(phoneNumber, builder.toString());
    return builder.toString();
}

results matching ""

    No results matching ""