JAvaは携帯電話の認証コードを送信して、アリ雲

27714 ワード

続きは、今回は携帯認証コードについて  ,使用するアリメールサポート
1、シーンを使う
モバイル端末やサイトへの登録、登録などの携帯電話番号の検証
2、手順
2.1、フロントエンド、携帯番号を記入し、送信認証コードをクリックする
2.2、サーバー、検証コードを生成し、アリインタフェースを呼び出して検証コードを送信し、検証コードと対応key(一般的に携帯電話番号)を保存する.
2.3、ユーザーがメールを受け取り、フロントエンドで入力し、フォームを提出する
2.4、サーバーは要求を受け取り、検証コードを検証し、業務を処理する
注意:アリメールの申請過程はここで説明しません.
プロファイルの設定:
alisms:
  accessKeyId: *******************
  accessSecret: **********************
  signName: *****
  templateCode: ***** //            
# , # idCardCode: SMS_18*****74 # # LoginCode: SMS_18*****73 # # LoginExceptionCode: SMS_187****72 # # userRegisterCode: SMS_187****71 # # updatePwdCode: SMS_187****70 # # changeInfoCode: SMS_18*****69 #

 
ツールクラス:
package com.*****.util.sendMessage;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.*******.vo.SendCodeDO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* @Description:          
* @Author:         Joe
* @CreateDate:     2020/3/21 15:49
*/
@Configuration
public class SendSmsUtil {
    //   keyID
    @Value("${alisms.accessKeyId}")
    private String accessKeyId;
    //     , keyID  
    @Value("${alisms.accessSecret}")
    private String accessSecret;
    //    -          
    @Value("${alisms.signName}")
    private String signName;
    //     -          
    @Value("${alisms.templateCode}")
    private String templateCode;
    //       ——        
    private static Map codeMap=new ConcurrentHashMap<>();
    //    
    private static final long expiredTime=1000*10*60;

    /************************    ********************************************
     http://dysmsapi.aliyuncs.com/?Signature=NAxwl1W9ROkidJfGeZrsKUXw%2BQ4%3D
     &AccessKeyId=testId
     &Action=SendSms
     &Format=XML
     &RegionId=cn-hangzhou
     &SignatureMethod=HMAC-SHA1
     &SignatureNonce=313ef0fb-0393-464f-a6e2-59d9ca2585b1
     &SignatureVersion=1.0
     &Timestamp=2019-01-08T08%3A18%3A18Z
     &Version=2017-05-25
     ***************************************************************************/


    /**
     * PhoneNumbers    
     * TemplateParam    
     * templateCode2     ——            
          :1、       ,    111111
             2、         ,    111111
     */
    public String aliSendSms(String PhoneNumbers,String TemplateParam,String templateCode2){
        String result = "";
        //  regionId:API   RegionID,   API   :cn-hangzhou;
        // AccessKey ID AccessKey Secret       API   ,          .
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //    
        request.setMethod(MethodType.POST);
        //    
        request.setDomain("dysmsapi.aliyuncs.com");

        //API     ,    YYYY-MM-DD。    :2017-05-25。
        request.setVersion("2017-05-25");

        //   :         ——  :SendSms。
        request.setAction("SendSms");

        request.putQueryParameter("RegionId", "cn-hangzhou");//     

        //  :      
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);

        //   :    -                、          
        request.putQueryParameter("SignName", signName);

        //   :    -          ;      、          ;     /      ,     /       。
        request.putQueryParameter("TemplateCode", templateCode2);

        //  :        JSON ,      "   ${name},      ${code}" ,     
        request.putQueryParameter("TemplateParam", TemplateParam);

        try {
            //           
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String infojson = response.getData();
            //      Map
            Gson gson2 = new Gson();
            Map map = gson2.fromJson(infojson, Map.class);
            String codes = map.get("Message").toString();
            System.out.println("codes="+codes);
            //         
            if(codes.equals("OK")){
                result="ok";
            }else {
                result="not_ok";
            }
        } catch (ServerException e) {
            //      
            e.printStackTrace();
        } catch (ClientException e) {
            //      
            e.printStackTrace();
        }
        //    
        System.out.println("result="+result);
        return result;
    }

    /**
     *          
      * @param key
     * @param code
     *@return ()
     *@throws
     *@author yutf
     *@date 2020/5/23
     *
     */
    public void saveMap(String key,String code){
        //     
        SendCodeDO sendCodeDO=new SendCodeDO();
        sendCodeDO.setCode(code);
        sendCodeDO.setSendTime(System.currentTimeMillis());
        codeMap.put(key,sendCodeDO);
    }

    /**
     *       ——        
      * @param PhoneNumbers
     * @param TemplateParam
     *@return ({@link java.lang.String})
     *@throws
     *@author yutf
     *@date 2020/5/23
     *
     */
    public String aliSendSms(String PhoneNumbers,String TemplateParam){
        String result = "";
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", TemplateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String infojson = response.getData();
            Gson gson2 = new Gson();
            Map map = gson2.fromJson(infojson, Map.class);
            String codes = map.get("Message").toString();
            System.out.println("codes="+codes);
            if(codes.equals("OK")){
                result="ok";
            }else {
                result="not_ok";
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        System.out.println("result="+result);
        return result;
    }

    /**
     *     
      * @param key
     * @param code
     *@return ({@link boolean})
     *@throws
     *@author yutf
     *@date 2020/5/23
     *
     */
    public static boolean verifyCode( String key,String code){
        //           
        cleanEmailMap();
        //             true    false
        if(codeMap.containsKey(key)){
           if(codeMap.get(key).getCode().equals(code)){
               return true;
           }
        }
        return false;
    }

    /**
     *
                
     *@return ()
     *@throws
     *@author yutf
     *@date 2020/5/23
     *
     */
    public static void cleanEmailMap() {
        //       
       if(!codeMap.isEmpty()){
           //    ——                           
           for (Map.Entry stringSendEmailDOEntry : codeMap.entrySet()) {
               if(((System.currentTimeMillis()-stringSendEmailDOEntry.getValue().getSendTime())>expiredTime)){
                   codeMap.remove(stringSendEmailDOEntry.getKey());
               }
           }
       }
    }

}

適用されるエンティティ
package com.*****.vo;

import lombok.Data;

/**
 *   :
 * 〈     〉
 *
 * @author ytf
 * @create 2020/4/22
 * @since 1.0.0
 */
@Data
public class SendCodeDO {
    private String code;
    private long sendTime;
}

 
使用例
 /**
     *      ——       
     * @param PhoneNumbers    
     * @return
     */
    @ApiOperation(value = "     ——  ;  ——   ")
    @GetMapping(value = "/sendSms")
    public ResultVo loginCodeSendSms(String PhoneNumbers){
        if(StringUtils.isBlank(PhoneNumbers)){
            return ResultVOUtils.error(ResultEnum.PARAM_VERIFY_FAIL,"       ");
        }
        //       
        String numeral = String.valueOf(new Random().nextInt(899999) + 100000);
        SmsData smsData = new SmsData(numeral);
     // Gson gson
= new Gson(); String code = gson.toJson(smsData); String information = sendSmsUtil.aliSendSms(PhoneNumbers, code, TypeConstant.ShortMessageType.loginCode.getCode()); String key=PhoneNumbers+TypeConstant.ShortMessageType.loginCode.getCode()+TypeConstant.PlatformType.app.getCode();
    // sendSmsUtil.saveMap(key,numeral);
if(information.equals("ok")){ return ResultVOUtils.success(" , "); } return ResultVOUtils.error(ResultEnum.NOT_NETWORK," , "); } /** * * @param PhoneNumbers * @param code * @return */ @ApiOperation(value = " : —— , ") @RequestMapping(value = "/loginCode/verifySms",method = RequestMethod.POST) public ResultVo loginCodeVerifySms(String PhoneNumbers, String code){ if(StringUtils.isBlank(PhoneNumbers)){ throw new JsonException(ResultEnum.PARAM_VERIFY_FAIL," "); } if(StringUtils.isBlank(code)){ throw new JsonException(ResultEnum.PARAM_VERIFY_FAIL," "); } String key=PhoneNumbers+TypeConstant.ShortMessageType.loginCode.getCode()+TypeConstant.PlatformType.app.getCode();
     //
boolean b = sendSmsUtil.verifyCode(key, code); if(b){ // ...... } return ResultVOUtils.error(ResultEnum.PARAM_VERIFY_FAIL," "); }

列挙クラスコード
 /**
     *     : 
* 〈 〉 # idCardCode: SMS_187*****74 # # LoginCode: SMS_187*****73 # # LoginExceptionCode: SMS_18****672 # # userRegisterCode: SMS_1*****671 # # updatePwdCode: SMS_18*****670 # # changeInfoCode: SMS_187*****69 # *
@return: * @since: 1.0.0 * @Author: * @Date: */ public enum ShortMessageType { idCardCode("SMS_18*****674"," "), loginCode("SMS_187****73"," "), loginExceptionCode("SMS_1875****2"," "), userRegisterCode("SMS_18******671"," "), updatePwdCode("SMS_187******70"," "), changeInfoCode("SMS_187*****69"," "); private String code; private String msg; private ShortMessageType(String code, String msg){ this.code =code; this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }