阿里雲短信驗證_基於阿里雲OpenAPI實現

阿里雲短信服務

背景簡介:

短信驗證以及短信通知,目前已經應用的很是普遍,最近因項目須要,須要將原來的短信接口換成阿里雲的的短信服務,原項目集成的短信服務可以實現短信的發送以及短信的驗證整個過程,簡單的來講,原來的短息服務,只需應用申請獲取短信,短息服務器會發送短信到指定的手機,用戶將驗證碼發送到短信服務商的服務器,服務器作出驗證返回是否經過,而阿里雲僅提供短信發送服務,須要本身開發短信的驗證。下面簡單的介紹一下:java

1.獲取阿里雲AccessKey

用戶->Accesskeys:須要本身建立一個AccessKeyweb

2.建立短信簽名:

阿里雲控制檯->短信服務->國內短信->簽名管理: 建立本身的簽名(簽名主要是指應用的名字,如:中國移動,建設銀行)api

3.建立短信模板:

國內短信->模板管理:建立本身的短信通知模板(如:您正在申請手機註冊,驗證碼爲:${code},5分鐘內有效!)tomcat

 

 

4.基於阿里雲openAPI實現短信發送模塊

注意:這裏項目中須要導入aliyun-java-sdk-core-4.1.0.jar,額外注意:javaweb項目中,須要將aliyun-java-sdk-core-4.1.0.jar 以及gson-2.8.5.jar 導入到tomcat 的lib目錄下,否則會出錯。服務器

 1 package Surpport;
 2 import com.aliyuncs.CommonRequest;
 3 import com.aliyuncs.CommonResponse;
 4 import com.aliyuncs.DefaultAcsClient;
 5 import com.aliyuncs.IAcsClient;
 6 import com.aliyuncs.exceptions.ClientException;
 7 import com.aliyuncs.exceptions.ServerException;
 8 import com.aliyuncs.http.MethodType;
 9 import com.aliyuncs.http.ProtocolType;
10 import com.aliyuncs.profile.DefaultProfile;
11 
12 
13 /*
14 pom.xml
15 <dependency>
16   <groupId>com.aliyun</groupId>
17   <artifactId>aliyun-java-sdk-core</artifactId>
18   <version>4.0.3</version>
19 </dependency>
20 */
21 
22 /****
23  *  阿里雲短信驗證工具
24  *  調用示例:
25  *  SmsUtil sednMessage = new SmsUtil();
26  *  sednMessage.SendSMS("手機號", "須要發送的驗證碼");
27  * @author finch
28  *
29  */
30 public class SmsUtil {
31     
32     
33     /*************阿里雲短信驗證參數*****************/
34     /******
35      * 參考 阿里雲 OpenAPI
36      * 
37      */
38     public String accessKeyId ="建立的AccessKeyId";     //AccessKeyId
39     public String accessSecret="獲取的AccessKeySecret";  //AccessKeySecret
40     public String  SignName ="短信簽名";                    //短信簽名名稱
41     public String  TemplateCode ="SMS_短信模板ID";         //短信模板ID
42     
43     
44      
45     public void SendSMS(String PhoneNumber,String RandomCode) {
46 
47 
48  DefaultProfile profile = DefaultProfile.getProfile("default",
49  accessKeyId,accessSecret); IAcsClient client = new DefaultAcsClient(profile);
50 
51     CommonRequest request = new CommonRequest();
52     request.setProtocol(ProtocolType.HTTPS);
53     request.setMethod(MethodType.POST);
54     request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25");
55     request.setAction("SendSms"); //短信發送類型:
56     request.putQueryParameter("PhoneNumbers", PhoneNumber); //接受短信的號碼
57     request.putQueryParameter("SignName", SignName); //短信簽名
58     request.putQueryParameter("TemplateCode",TemplateCode ); //短信模板id
59     request.putQueryParameter("TemplateParam", "{\"code\":\""+RandomCode+"\"}"); //隨機驗證碼
60    try { CommonResponse response = client.getCommonResponse(request);
61         System.out.println(response.getData()); //調用結果顯示 
62         }  catch (ServerException e)
63       { 
64             e.printStackTrace(); 
65        } catch (ClientException e) 
66    { e.printStackTrace(); }
67 
68     }
69 }

 

5.實現短信驗證流程

相關文章
相關標籤/搜索