Access to Tencent Cloud SMS service (the most detailed in history + how to successfully apply for this SMS service + API explanation for sending SMS verification code + related error analysis)

2021 / 8 / 17 / 23 : 01 {2021/8/17/23:01} 2021/8/17/23:01


foreword

Some people may ask me why I don't use the Alibaba Cloud SMS service. That is because the current Alibaba Cloud SMS service is difficult for most people to apply for successfully. It needs to be filed or the project has been launched. However, Tencent Cloud SMS is relatively loose, and you can use your personal public account to apply successfully.


Reminder: The following is the main text of this article

1. How to successfully apply for Tencent Cloud SMS Service

First open the SMS service, you should be given 100 SMS for free
Please add image description

1. Sign the application

I have tested the application once {I have tested the application once}I have already tested the application once
Please add image description
Click Create Signature
Please add image description

WeChat official account platform link: https://www.baidu.com/link?url=3OqiiGcBpe8Gp5YpnN4wF7CiaFkigOjrPtN3xjuIWLF1EDlRASXa3EDgeaQNn8k6&wd=&eqid=d95710f900018b6500000003611bd16a

Please add image description

2. Application for text template

Click to create a text template
Please add image description
Please add image description
and wait for review



Second, send SMS API development

1. Tencent cloud online test

Online test first, then use code test

Test address : https://console.cloud.tencent.com/api/explorer?Product=sms&Version=2021-01-11&Action=SendSms&SignVersion=
Please add image description

Please add image description

1. SmsSdkAppId: SMS SdkAppId, the actual SdkAppId generated after adding the application in the SMS console
Please add image description
2. TemplateId: Template ID, the template ID that has been approved must be filled in. The template ID can be viewed by logging in to the SMS console. If you send SMS to an overseas mobile phone number, only international/Hong Kong, Macau, and Taiwan SMS templates are supported.
Please add image description
3. SignName: The content of the SMS signature, using UTF-8 encoding, must fill in the approved signature, for example: Tencent Cloud, the signature information can be viewed by logging in to the SMS console. Domestic SMS is a required parameter.
Please add image description

Click to send request

Please add image description

Please add image description
Please add image description
success!

2. Use springboot for testing

1. Document reference preparation

You can generate code directly in the cloud
Please add image description
or refer to the API documentation

API documentation link address: https://cloud.tencent.com/document/product/382/43194

Please add image description
2. Import dependencies

       <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
        </dependency>

Please add image description

3. a p p l i c a t i o n . y m l {application.yml} a p p l i c a t i o n . y ml file writing
Please add image description

4. Create a tool class

//实现了InitializingBean接口,当spring进行初始化bean时,会执行afterPropertiesSet方法
@Component
public class MsmConstantUtils implements InitializingBean {
    
    
	//我已经再
    @Value("${tencent.msm.id}")
    private String secretID ;

    @Value("${tencent.msm.secret}")
    private String secretKey ;

    @Value("${tencent.msm.endPoint}")
    private String endPoint;

    @Value("${tencent.msm.appId}")
    private String appId;

    @Value("${tencent.msm.signName}")
    private String signName;

    @Value("${tencent.msm.templateId}")
    private String templateId;
    //六个相关的参数
    public static String SECRET_ID;
    public static String SECRET_KEY;
    public static String END_POINT;
    public static String APP_ID;
    public static String SIGN_NAME;
    public static String TEMPLATE_ID;
 
    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        SECRET_ID = secretID;
        SECRET_KEY = secretKey;
        END_POINT = endPoint;
        APP_ID = appId;
        SIGN_NAME = signName;
        TEMPLATE_ID = templateId;
    }
}

5. RandomUtil writing

public class RandomUtil {
    
    

    private static final Random random = new Random();
//我定义的验证码位数是6位
    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getSixBitRandom() {
    
    
        return sixdf.format(random.nextInt(1000000));
    }
}

6. Interface writing

Note that the project I am looking for has integrated Swagger configuration, and I need to test it later

@RestController
@RequestMapping("/msm")
@CrossOrigin
@Api("发送短信服务")
public class MsmController {
    
    

    @Autowired
    private MsmService msmService;

    @ApiOperation("发送短信")
    @GetMapping("/send/{phone}")
    public ResponseEntity send(@PathVariable String phone) {
    
    

        boolean send = msmService.send(phone);
        if (send) {
    
    
            return ResponseEntity.ok();
        }
        return ResponseEntity.error();
    }
}
import com.tencentcloudapi.common.Credential;
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.zhang.service.MsmService;
import com.zhang.utils.MsmConstantUtils;
import com.zhang.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author:zsh
 * @date:2021/8/18
 * @email:[email protected]
 */
@Service
@Slf4j
public class MsmServiceImpl implements MsmService {
    
    
    @Override
    public boolean send(String phone) {
    
    
        try {
    
    
            //这里是实例化一个Credential,也就是认证对象,参数是密钥对;你要使用肯定要进行认证
            Credential credential = new Credential(MsmConstantUtils.SECRET_ID, MsmConstantUtils.SECRET_KEY);

            //HttpProfile这是http的配置文件操作,比如设置请求类型(post,get)或者设置超时时间了、还有指定域名了
            //最简单的就是实例化该对象即可,它的构造方法已经帮我们设置了一些默认的值
            HttpProfile httpProfile = new HttpProfile();
            //这个setEndpoint可以省略的
            httpProfile.setEndpoint(MsmConstantUtils.END_POINT);

            //实例化一个客户端配置对象,这个配置可以进行签名(使用私钥进行加密的过程),对方可以利用公钥进行解密
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            //实例化要请求产品(以sms为例)的client对象
            SmsClient smsClient = new SmsClient(credential, "ap-beijing", clientProfile);

            //实例化request封装请求信息
            SendSmsRequest request = new SendSmsRequest();
            String[] phoneNumber = {
    
    phone};
            request.setPhoneNumberSet(phoneNumber);     //设置手机号
            request.setSmsSdkAppid(MsmConstantUtils.APP_ID);
            request.setSign(MsmConstantUtils.SIGN_NAME);
            request.setTemplateID(MsmConstantUtils.TEMPLATE_ID);
            //生成随机验证码,我的模板内容的参数只有一个
            String verificationCode = RandomUtil.getSixBitRandom();
            String[] templateParamSet = {
    
    verificationCode};
            request.setTemplateParamSet(templateParamSet);

            //发送短信
            SendSmsResponse response = smsClient.SendSms(request);
            log.info(SendSmsResponse.toJsonString(response));
            return true;
        } catch (Exception e) {
    
    
            return false;
        }


    }
}

7. Test
Please add image description

Visit http://localhost:8005/swagger-ui.html

Use swagger to test and you can
Please add image description
Please add image description
Please add image description
succeed!



Three, common error analysis

FailedOperation.TemplateIncorrectOrUnapproved appears when using Tencent Cloud SMS technology https://blog.csdn.net/Kevinnsm/article/details/119767325?spm=1001.2014.3001.5501
There are both domestic mobile phone numbers and international mobile phone numbers in the… https://blog.csdn.net/Kevinnsm/article/details/119767611?spm=1001.2014.3001.5501


It's over! ❤️

2021/8/18/0:54

Guess you like

Origin blog.csdn.net/Kevinnsm/article/details/119768203