腾讯云短信发送案例

准备阶段

1.开通腾讯云短信服务

具体如何开通本文不做讲解,想了解的可参考:开通腾讯云短息服务

2.yml文件中的配置

dts:
 #通知相关配置
  notify:
   # 短消息模版通知配置
    # 短信息用于通知客户,例如发货短信通知,注意配置格式;template-name,template-templateId 请参考 NotifyType 枚举值
    sms:
      enable: true
      appid: 你的申请的apid
      appkey: 你申请的密钥
      template:
      - name: paySucceed
        templateId: 短信模版id
      - name: captcha
        templateId: 短信模版id
      - name: ship
        templateId: 短信模版id
      - name: refund
        templateId: 短信模版id

3.需要的依赖

		<dependency>
			<groupId>com.github.qcloudsms</groupId>
			<artifactId>qcloudsms</artifactId>
			<version>1.0.6</version>
		</dependency>

		<dependency>
			<groupId>com.github.binarywang</groupId>
			<artifactId>weixin-java-miniapp</artifactId>
			<version>3.6.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>2.0.17</version>
		</dependency>

前期的准备做好了,相信小伙伴们应该都准备好了吧,下面咱们就开始进行代码开发

代码开发阶段

1.新建一个通知需要的实体类

package cn.ahwlan.maintenance.core.notify.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ConfigurationProperties(prefix = "dts.notify")
public class NotifyProperties {
	private Sms sms;
	
	public static class Sms {
		private boolean enable;
		private int appid;
		private String appkey;
		private List<Map<String, String>> template = new ArrayList<>();

		public boolean isEnable() {
			return enable;
		}

		public void setEnable(boolean enable) {
			this.enable = enable;
		}

		public int getAppid() {
			return appid;
		}

		public void setAppid(int appid) {
			this.appid = appid;
		}

		public String getAppkey() {
			return appkey;
		}

		public void setAppkey(String appkey) {
			this.appkey = appkey;
		}

		public List<Map<String, String>> getTemplate() {
			return template;
		}

		public void setTemplate(List<Map<String, String>> template) {
			this.template = template;
		}
	}
}

2.新建配置类

package cn.ahwlan.maintenance.core.notify.config;

import cn.ahwlan.maintenance.core.notify.NotifyService;
import cn.ahwlan.maintenance.core.notify.TencentSmsSender;
import com.github.qcloudsms.SmsSingleSender;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(NotifyProperties.class)
public class NotifyAutoConfiguration {

	private final NotifyProperties properties;

	public NotifyAutoConfiguration(NotifyProperties properties) {
		this.properties = properties;
	}

	@Bean
	public NotifyService notifyService() {
		NotifyService notifyService = new NotifyService();
		NotifyProperties.Sms smsConfig = properties.getSms();
		if (smsConfig.isEnable()) {
			notifyService.setSmsSender(tencentSmsSender());
			notifyService.setSmsTemplate(smsConfig.getTemplate());
		}
		return notifyService;
	}

	@Bean
	public TencentSmsSender tencentSmsSender() {
		NotifyProperties.Sms smsConfig = properties.getSms();
		TencentSmsSender smsSender = new TencentSmsSender();
		smsSender.setSender(new SmsSingleSender(smsConfig.getAppid(), smsConfig.getAppkey()));
		return smsSender;
	}
}

3.通知枚举类

具体参数根据业务配置,每个类型对应个短信模版id

package cn.ahwlan.maintenance.core.notify;

public enum NotifyType {
	PAY_SUCCEED("paySucceed"), SHIP("ship"), APPLYREFUND("applyRefund"), // 申请退款
	REFUND("refund"), CAPTCHA("captcha");

	private String type;

	NotifyType(String type) {
		this.type = type;
	}

	public String getType() {
		return this.type;
	}
}

4.发送短信接口

package cn.ahwlan.maintenance.core.notify;

public interface SmsSender {

	/**
	 * 发送短信息
	 *
	 * @param phone
	 *            接收通知的电话号码
	 * @param content
	 *            短消息内容
	 */
	SmsResult send(String phone, String content);

	/**
	 * 通过短信模版发送短信息
	 *
	 * @param phone
	 *            接收通知的电话号码
	 * @param templateId
	 *            通知模板ID
	 * @param params
	 *            通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
	 */
	SmsResult sendWithTemplate(String phone, int templateId, String[] params);
}

5.实现类

package cn.ahwlan.maintenance.core.notify;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

/*
 * 腾讯云短信服务
 */
public class TencentSmsSender implements SmsSender {
	private final Log logger = LogFactory.getLog(TencentSmsSender.class);

	private SmsSingleSender sender;

	public SmsSingleSender getSender() {
		return sender;
	}

	public void setSender(SmsSingleSender sender) {
		this.sender = sender;
	}

	@Override
	public SmsResult send(String phone, String content) {
		try {
			SmsSingleSenderResult result = sender.send(0, "86", phone, content, "", "");
			logger.debug(result);

			SmsResult smsResult = new SmsResult();
			smsResult.setSuccessful(true);
			smsResult.setResult(result);
			return smsResult;
		} catch (HTTPException | IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public SmsResult sendWithTemplate(String phone, int templateId, String[] params) {
		try {
			SmsSingleSenderResult result = sender.sendWithParam("86", phone, templateId, params, "公司名称", "", "");
			logger.debug(result);

			SmsResult smsResult = new SmsResult();
			smsResult.setSuccessful(true);
			smsResult.setResult(result);
      System.out.println(smsResult.getResult()+"!===========!");
			return smsResult;
		} catch (HTTPException | IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}

6.消息通知类

package cn.ahwlan.maintenance.core.notify;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息通知服务类
 */
public class NotifyService {
	private String sendFrom;
	private String sendTo;

	private SmsSender smsSender;
	private List<Map<String, String>> smsTemplate = new ArrayList<>();

	/**
	 * 短讯服务是否启动
	 * @return
	 */
	public boolean isSmsEnable() {
		return smsSender != null;
	}


	/**
	 * 短信消息通知
	 *
	 * @param phoneNumber
	 *            接收通知的电话号码
	 * @param message
	 *            短消息内容,这里短消息内容必须已经在短信平台审核通过
	 */
	@Async
	public void notifySms(String phoneNumber, String message) {
		if (smsSender == null)
			return;

		smsSender.send(phoneNumber, message);
	}

	/**
	 * 短信模版消息通知
	 *
	 * @param phoneNumber
	 *            接收通知的电话号码
	 * @param notifyType
	 *            通知类别,通过该枚举值在配置文件中获取相应的模版ID
	 * @param params
	 *            通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
	 */
	@Async
	public SmsResult notifySmsTemplate(String phoneNumber, NotifyType notifyType, String[] params) {
		if (smsSender == null) {
			return null;
		}

		String templateIdStr = getTemplateId(notifyType, smsTemplate);
		if (templateIdStr == null) {
			return null;
		}

		int templateId = Integer.parseInt(templateIdStr);
		return smsSender.sendWithTemplate(phoneNumber, templateId, params);
	}

	/**
	 * 以同步的方式发送短信模版消息通知
	 *
	 * @param phoneNumber
	 *            接收通知的电话号码
	 * @param notifyType
	 *            通知类别,通过该枚举值在配置文件中获取相应的模版ID
	 * @param params
	 *            通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
	 * @return
	 */
	public SmsResult notifySmsTemplateSync(String phoneNumber, NotifyType notifyType, String[] params) {
		if (smsSender == null)
			return null;

		int templateId = Integer.parseInt(getTemplateId(notifyType, smsTemplate));

		return smsSender.sendWithTemplate(phoneNumber, templateId, params);
	}

	private String getTemplateId(NotifyType notifyType, List<Map<String, String>> values) {
		for (Map<String, String> item : values) {
			String notifyTypeStr = notifyType.getType();

			if (item.get("name").equals(notifyTypeStr))
				return item.get("templateId");
		}
		return null;
	}

	public void setSendFrom(String sendFrom) {
		this.sendFrom = sendFrom;
	}

	public void setSendTo(String sendTo) {
		this.sendTo = sendTo;
	}

	public void setSmsSender(SmsSender smsSender) {
		this.smsSender = smsSender;
	}

	public void setSmsTemplate(List<Map<String, String>> smsTemplate) {
		this.smsTemplate = smsTemplate;
	}
}

7.返回结果类

package cn.ahwlan.maintenance.core.notify;

/**
 * 发送短信的返回结果
 */
public class SmsResult {
	private boolean successful;
	private Object result;

	/**
	 * 短信是否发送成功
	 *
	 * @return
	 */
	public boolean isSuccessful() {
		return successful;
	}

	public void setSuccessful(boolean successful) {
		this.successful = successful;
	}

	public Object getResult() {
		return result;
	}

	public void setResult(Object result) {
		this.result = result;
	}

	@Override
	public String toString() {
		return "SmsResult{" +
				"successful=" + successful +
				", result=" + result +
				'}';
	}
}

8.创建个controller实现

package cn.ahwlan.maintenance.core.controller;

import cn.ahwlan.maintenance.core.notify.NotifyService;
import cn.ahwlan.maintenance.core.notify.NotifyType;
import cn.ahwlan.maintenance.core.notify.SmsResult;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sms")
public class SmsSendController {

    private static final Logger logger = LoggerFactory.getLogger(SmsSendController.class);

    @Autowired
    private NotifyService notifyService;

    @PostMapping("/send")
    @ApiOperation(value = "",nickname = "smsSend")
    public Object send(String phoneNumber){
        SmsResult smsResult = notifyService.notifySmsTemplate(phoneNumber, NotifyType.CAPTCHA, new String[]{"1", "2"});
        if (smsResult != null) {
            logger.info("短信发送结果:{}", JSONObject.toJSONString(smsResult));
        }
        return smsResult;
    }
}

结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值