腾讯云短信申请与使用

目录

一、申请微信公众号

1.网页搜索微信公众平台

 2.注册

3.类型选择订阅号 

4.信息登记为个人

 二、进入腾讯云创建签名管理和正文模板

1.网页搜索腾讯云官网

2.选择国内短信

3.申请签名管理(不太好申请)

4.创建正文模板(使用标准模板)比较好申请​

5.通过官方文档使用腾讯云短信(下面有自己写的代码)

6.在IDEA中使用 

6.1引入依赖

 6.2创建工具类

 6.3创建controller

6.4service和serviceImpl

6.5调用随机验证码的工具类

6.6最后使用swagger页面测试即可

导入swagger依赖

在测试之前需要开启Linux上的redis


一、申请微信公众号

1.网页搜索微信公众平台

 2.注册

使用邮箱注册,并绑定基本信息

3.类型选择订阅号 

4.信息登记为个人

接下来就是公众号名称与功能介绍  和设置公众号(越简洁越容易记越好) 

 创建成功之后,更换头像和名称(刚注册成功之后,三天内名称不换则自动注销)

更改功能设置(允许通过名称搜索到本账号)

 二、进入腾讯云创建签名管理和正文模板

1.网页搜索腾讯云官网

进入后搜索短信

2.选择国内短信

3.申请签名管理(不太好申请)

 刚开始通过名称搜索不到公众号,但通过微信号可以搜索到

4.创建正文模板(使用标准模板)比较好申请

5.通过官方文档使用腾讯云短信(下面有自己写的代码)

6.在IDEA中使用 

6.1引入依赖

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

 6.2创建工具类

package com.chang.msmservice.utils;

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.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;

public class TxCode {
    private static final String SECRET_ID = "主页搜索API密钥管理(SecretId)";
    private static final String SECRET_KEY= "主页搜索API密钥管理(SecretKey)";

    public static boolean SendCode(String phoneNumber,String code) {
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
           ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            /* SDK默认用TC3-HMAC-SHA256进行签名
             * 非必要请不要修改这个字段 */
            clientProfile.setSignMethod("HmacSHA256");
            /* 实例化要请求产品(以sms为例)的client对象
             * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */
            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet = {phoneNumber};
            req.setPhoneNumberSet(phoneNumberSet);

            req.setSmsSdkAppId("应用管理中应用列表的sdk。。");
            req.setSignName("签名管理内容的名字");
            req.setTemplateId("正文模板id");

            String[] templateParamSet = {code};
            req.setTemplateParamSet(templateParamSet);

            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);

            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));

            //获取发送状态,若成功则返回true
            for (SendStatus sendStatus : resp.getSendStatusSet()) {
                if ("send success".equals(sendStatus.getMessage()) &&
                        "Ok".equals(sendStatus.getCode())){
                    return true;
                }
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        //若不成,返回false
        return false;
    }
}

 6.3创建controller

public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    @GetMapping("send/{phone}")
    public R  send(@PathVariable String  phone){
       //1.从redis获取验证码,如果获取到直接返回
        String code=redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //若Redis中没有,调用service发送短信方法
        boolean res = msmService.send(phone);

        if (res){
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }
    }
}

6.4service和serviceImpl

public interface MsmService {

    boolean send( String phone);
}

@Service
public class MsmServiceImpl implements MsmService{
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信方法
     */
    @Override
    public boolean send(String phone) {
        //生成四位数验证码交腾讯云发送
        String code = RandomUtil.getFourBitRandom();

        //发送验证码
        boolean res = TxCode.SendCode("+86" + phone, code);

        if (res){
            //发送成功后将验证码放到Redis中设置存活时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return true;
        }else {
            throw new GuliException(20001,"验证码发送失败");
        }

    }


}

6.5调用随机验证码的工具类

public class RandomUtil {

	private static final Random random = new Random();

	private static final DecimalFormat fourdf = new DecimalFormat("0000");

	private static final DecimalFormat sixdf = new DecimalFormat("000000");

	public static String getFourBitRandom() {
		return fourdf.format(random.nextInt(10000));
	}

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

	/**
	 * 给定数组,抽取n个数据
	 * @param list
	 * @param n
	 * @return
	 */
	public static ArrayList getRandom(List list, int n) {

		Random random = new Random();

		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

		// 生成随机数字并存入HashMap
		for (int i = 0; i < list.size(); i++) {

			int number = random.nextInt(100) + 1;

			hashMap.put(number, i);
		}

		// 从HashMap导入数组
		Object[] robjs = hashMap.values().toArray();

		ArrayList r = new ArrayList();

		// 遍历数组并打印数据
		for (int i = 0; i < n; i++) {
			r.add(list.get((int) robjs[i]));
			System.out.print(list.get((int) robjs[i]) + "\t");
		}
		System.out.print("\n");
		return r;
	}
}

6.6最后使用swagger页面测试即可

导入swagger依赖


            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>${swagger.version}</version>
            </dependency>
            <!--swagger ui-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>${swagger.version}</version>
            </dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket webApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")//swagger右上角的名字
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();

    }

    private ApiInfo webApiInfo(){

        return new ApiInfoBuilder()
                .title("网站-课程中心API文档")
                .description("本文档描述了课程中心微服务接口定义")
                .version("2.0")
                .contact(new Contact("ZUA", "http://zua.edu.cn", "2658098903@qq.com"))
                .build();
    }
}

在测试之前需要开启Linux上的redis

 


版权声明:本文为m0_51505198原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。