Răsfoiți Sursa

腾讯手机号

licailing 5 ani în urmă
părinte
comite
c5a67a9f4e

+ 8 - 2
src/main/java/com/izouma/dingdong/service/UserService.java

@@ -39,7 +39,7 @@ public class UserService {
     private UserRepo       userRepo;
     private WxMaService    wxMaService;
     private WxMpService    wxMpService;
-//    private SmsService     smsService;
+    private SmsService     smsService;
     private StorageService storageService;
     private JwtTokenUtil   jwtTokenUtil;
 
@@ -102,7 +102,13 @@ public class UserService {
         return userRepo.save(user);
     }
 
-    public User loginByPhone(String phone) {
+    public User loginByPhone(String phone, String code) {
+        try {
+            smsService.verify(phone, code);
+        } catch (SmsService.SmsVerifyException e) {
+            e.printStackTrace();
+            throw new BusinessException("验证码错误");
+        }
         User user = userRepo.findByPhone(phone);
         if (user == null) {
             user = User.builder()

+ 39 - 28
src/main/java/com/izouma/dingdong/service/sms/TencentSmsService.java

@@ -6,17 +6,18 @@ import com.izouma.dingdong.repo.SmsRecordRepo;
 import com.izouma.dingdong.service.sms.SmsService;
 import com.tencentcloudapi.common.Credential;
 import com.tencentcloudapi.common.exception.TencentCloudSDKException;
+import com.tencentcloudapi.common.profile.ClientProfile;
+import com.tencentcloudapi.common.profile.HttpProfile;
 import com.tencentcloudapi.sms.v20190711.SmsClient;
-import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
-import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
-import com.tencentcloudapi.sms.v20190711.models.SendStatus;
+import com.tencentcloudapi.sms.v20190711.models.*;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
-import javax.websocket.SendResult;
 import java.time.LocalDateTime;
+import java.time.ZoneOffset;
 
 /**
  * Tencent Cloud Sms Sendsms
@@ -31,51 +32,61 @@ public class TencentSmsService {
     private String        secretKey;
     @Value("${tencent.sms_appid}")
     private String        appId;
+    @Autowired
     private SmsRecordRepo smsRecordRepo;
 
 
-    public String sendVerify(String phone) {
-        // 短信模板ID,需要在短信应用中申请
-        String templateId = "676939";
+    public String sendVerify(String phone, String templateId) {
         // 签名,使用的是`签名内容`,而不是`签名ID`
         String smsSign = "弗雷登";
-        String[] phones = {phone};
 
-        String[] param = {RandomStringUtils.randomNumeric(4)};
+        String param = RandomStringUtils.randomNumeric(4);
+
         try {
-            //发送请求
-            SendSmsRequest req = new SendSmsRequest();
-            req.setPhoneNumberSet(phones);
-            req.setTemplateID(templateId);
-            req.setSign(smsSign);
-            req.setSmsSdkAppid(appId);
-            req.setTemplateParamSet(param);
-            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
+            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
             Credential cred = new Credential(secretId, secretKey);
-            //实例化要请求产品的client对象,clientProfile是可选的
-            SmsClient client = new SmsClient(cred, "");
-            client.SendSms(req);
-            SendSmsResponse resp = client.SendSms(req);
+            //请求
+            HttpProfile httpProfile = new HttpProfile();
+            httpProfile.setEndpoint("sms.tencentcloudapi.com");
 
-            SendStatus sendStatus = resp.getSendStatusSet()[0];
-            String code = sendStatus.getCode();
-            if (!code.equals("Ok")) {
-                throw new BusinessException("发送失败,请稍后再试", code + "," + sendStatus.getMessage());
+            ClientProfile clientProfile = new ClientProfile();
+            clientProfile.setHttpProfile(httpProfile);
+
+            SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);
+
+            String params = "{\"PhoneNumberSet\":[\"" + phone
+                    + "\"],\"TemplateID\":\"" + templateId
+                    + "\",\"Sign\":\"" + smsSign
+                    + "\",\"TemplateParamSet\":[\"" + param
+                    + "\"],\"SmsSdkAppid\":\"" + appId + "\"}";
+            //发送请求
+            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);
+            //回调
+            SendSmsResponse resp = client.SendSms(req);
+            String s = SendSmsResponse.toJsonString(resp);
+            SendStatus status = resp.getSendStatusSet()[0];
+            if (!status.getCode().equals("Ok")) {
+                throw new BusinessException("发送失败,请稍后再试", status.getCode() + "," + status.getMessage());
             }
+            //报错到sms表
             smsRecordRepo.expire(phone);
-            String sessionId = RandomStringUtils.randomAlphabetic(10);
+//            String sessionId = RandomStringUtils.randomAlphabetic(10);
+            String sessionId = resp.getRequestId();
             smsRecordRepo.save(SmsRecord.builder()
                     .sessionId(sessionId)
                     .phone(phone)
-                    .code(param[0])
+                    .code(param)
                     .expiresAt(LocalDateTime.now().plusMinutes(5))
                     .expired(false)
                     .build());
-            return sessionId;
 
+            System.out.println(s);
+            return sessionId;
         } catch (TencentCloudSDKException e) {
             e.printStackTrace();
             throw new BusinessException("发送失败,请稍后再试", e.getMessage());
         }
+
     }
+
 }

+ 3 - 3
src/main/java/com/izouma/dingdong/web/AuthenticationController.java

@@ -49,9 +49,9 @@ public class AuthenticationController {
 
     @PostMapping("/phoneLogin")
     @ApiOperation(value = "手机号登录")
-    public String phoneLogin(String phone) {
+    public String phoneLogin(String phone, String code) {
         try {
-            User user = userService.loginByPhone(phone);
+            User user = userService.loginByPhone(phone, code);
             return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
         } catch (Exception e) {
             log.error("loginByPhone", e);
@@ -100,7 +100,7 @@ public class AuthenticationController {
 
     @PostMapping("/loginByRegister")
     @ApiOperation("注册登录")
-    public String loginByRegister(String phone, String password,Identity identity) {
+    public String loginByRegister(String phone, String password, Identity identity) {
         try {
             User user = userService.register(phone, password, identity);
             return jwtTokenUtil.generateToken(JwtUserFactory.create(user));

+ 16 - 2
src/main/java/com/izouma/dingdong/web/SmsController.java

@@ -32,11 +32,25 @@ public class SmsController {
         smsService.verify(phone, code);
     }
 
+    /**
+     * 腾讯发送短信
+     *
+     * @param phone      需要加+86
+     * @param templateId 短信模板
+     *                   676939 -修改手机号
+     *                   674906 -注册
+     *                   674851 -通用
+     *                   674832 -忘记密码
+     *                   -----国际----
+     *                   674908 -通用
+     *                   674903 -注册
+     * @return sessionId
+     */
     @GetMapping("/tencentSend")
-    public String tencentSend(@RequestParam String phone) {
+    public String tencentSend(@RequestParam String phone, String templateId) {
         if (!Pattern.matches(Constants.Regex.PHONE, phone)) {
             throw new BusinessException("请输入正确的手机号");
         }
-        return tencentSmsService.sendVerify(phone);
+        return tencentSmsService.sendVerify(phone, templateId);
     }
 }

+ 0 - 1
src/main/resources/application.yaml

@@ -90,7 +90,6 @@ tencent:
   secret_id: AKIDNZU9ZiEJn03rPgNNq1wbhXIo43nFpqRl
   secret_key: OWZNuCNK2UorFOG5mGXYCakenjfBAsZ0
   sms_appid: 1400405705
-  sms_appkey: dd98bf6e6dc2f1f481702d1d5a303ddb
 ---
 
 spring:

+ 1 - 1
src/main/vue/src/views/Login.vue

@@ -220,7 +220,7 @@ export default {
             }
             this.sending = true;
             this.$http
-                .get("/sms/tencentSend", {
+                .get("/sms/sendVerify", {
                     phone: this.userInfo.phone
                 })
                 .then(res => {

+ 3 - 3
src/test/java/com/izouma/dingdong/service/sms/TencentSmsTest.java

@@ -12,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.junit4.SpringRunner;
 
-import javax.websocket.SendResult;
 
 @RunWith(SpringRunner.class)
 @SpringBootTest
@@ -58,7 +57,8 @@ public class TencentSmsTest {
 
     @Test
     public void test1(){
-        SendResult result = new SendResult();
-        System.out.println(result.isOK());
+      // smsService.pullSmsSend("+8613182976895");
+        System.out.println(smsService.sendVerify("+8618205083565"));
+
     }
 }