当前位置: 首页 > news >正文

华为云短信接入实现示例

1)构建Springboot项目

2)  添加依赖

<dependency><groupId>com.huawei.apigateway</groupId><artifactId>java-sdk-core</artifactId><version>3.2.4</version>
</dependency>

3) 配置文件

huaweiyun:sms:url: https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1appKey: V******************0appSecret: X*******************vsender: 8***********9

4) 配置类

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.lang.reflect.Field;
import java.lang.reflect.Modifier;/*** @author admin*/
@Component
public class SmsConstant implements InitializingBean {@Value("${huaweiyun.sms.url}")public String smsUrl;@Value("${huaweiyun.sms.appKey}")public String appKey;@Value("${huaweiyun.sms.appSecret}")public String appSecret;@Value("${huaweiyun.sms.sender}")public String smsSender;public static String APP_KEY;public static String APP_SECRET;public static String SMS_URL;public static String SMS_SENDER;@Overridepublic void afterPropertiesSet(){APP_KEY = appKey;APP_SECRET = appSecret;SMS_URL = smsUrl;SMS_SENDER = smsSender;}/** 为了解决base64加密 密钥太长报错问题*/static {try {Class<?> clazz = Class.forName("javax.crypto.JceSecurity");Field nameField = clazz.getDeclaredField("isRestricted");Field modifiersField = Field.class.getDeclaredField("modifiers");modifiersField.setAccessible(true);modifiersField.setInt(nameField, nameField.getModifiers() & ~Modifier.FINAL);nameField.setAccessible(true);nameField.set(null, Boolean.FALSE);} catch (Exception ex) {ex.printStackTrace();}}
}

5)使用枚举类定义短信模板

@AllArgsConstructor
@Getter
public enum MsgTempEnum {SMS_VERIFY(1, "短信认证","SMS_VERIFY"),FIRE_PUSH_SMS(2, "短信推送","PUSH_SMS"),;private final int id;private final String name;private final String code;}

6)短信工具类

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.zxzx.firecloud.module.base.model.entity.Message;
import com.zxzx.firecloud.module.base.model.entity.TempSms;
import com.zxzx.firecloud.module.base.service.IMessageService;
import com.zxzx.firecloud.module.base.service.ITempSmsService;
import com.zxzx.firecloud.module.uc.model.entity.User;
import com.zxzx.firecloud.module.uc.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;/*** @author admin*/
@Slf4j
@Component
public class SendSms {public static final String UTF_8 = "UTF-8";@Autowiredprivate IMessageService messageService;@Autowiredprivate ITempSmsService tempSmsService;@Autowiredprivate IUserService userService;public List<SmsResultDetail> sendSms(MsgTempEnum msgTempEnum, String receiver, String param) {return sendSms(msgTempEnum, Collections.singletonList(receiver), Collections.singletonList(param));}public List<SmsResultDetail> sendSms(MsgTempEnum msgTempEnum, List<String> receiverList, String param) {return sendSms(msgTempEnum, receiverList, Collections.singletonList(param));}public List<SmsResultDetail> sendSms(MsgTempEnum msgTempEnum, String receiver, List<String> paramList) {return sendSms(msgTempEnum, Collections.singletonList(receiver), paramList);}public List<SmsResultDetail> sendSms(MsgTempEnum msgTempEnum, List<String> receiverList, List<String> paramList) {try {TempSms tempSms = tempSmsService.getTempSmsByBusiness(msgTempEnum.getCode());String templateId = tempSms.getTemplateId();if (ObjUtil.isEmpty(receiverList) || ObjUtil.isEmpty(templateId)) {log.error("receiverList or templateId is null");return new ArrayList<>();}String templateParas = "[\"" + StringUtils.join(paramList, "\",\"") + "\"]";String receiver = StringUtils.join(receiverList, ",");List<SmsResultDetail> responseList = new ArrayList<>();try {Request request = new Request();String body = buildRequestBody(SmsConstant.SMS_SENDER, receiver, templateId, templateParas);request.setKey(SmsConstant.APP_KEY);request.setSecret(SmsConstant.APP_SECRET);request.setUrl(SmsConstant.SMS_URL);request.setMethod("POST");request.addHeader("Content-Type", "application/x-www-form-urlencoded");request.setBody(body);HttpRequestBase signedRequest = Client.sign(request, "SDK-HMAC-SHA256");HttpResponse response = HttpClientSingleton.getInstance().execute(signedRequest);log.info("Print the status line of the response: {}", response.getStatusLine().toString());responseList = getResultDetailList(response.getEntity());} catch (Exception e) {log.error(e.getMessage(), e);}for (SmsResultDetail resultDetail : responseList) {Message message = new Message();message.setMessageType("SMS");message.setMessageContent(MessageFormat.format(tempSms.getTemplateDesc(), paramList.toArray()));message.setTitle(tempSms.getName());message.setReceiver(resultDetail.getOriginTo());message.setCallMessage(resultDetail.toString());message.setBusiness(msgTempEnum.getCode());message.setStatus(2);if ("000000".equals(resultDetail.getStatus())) {message.setStatus(1);}messageService.save(message);}return responseList;} catch (Exception e) {log.error("短信推送失败:{}", e);return new ArrayList<>();}}private static List<SmsResultDetail> getResultDetailList(HttpEntity resEntity) throws IOException {if (resEntity == null) {return new ArrayList<>();}String res = EntityUtils.toString(resEntity, "UTF-8");log.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"), res);SmsResult bean = JSONUtil.toBean(res, SmsResult.class);if (bean == null || !"000000".equals(bean.getCode())) {return new ArrayList<>();}List<SmsResultDetail> successList = new ArrayList<>();if (ObjUtil.isNotEmpty(bean.getResult())) {successList = bean.getResult();}return successList;}static String buildRequestBody(String sender, String receiver, String templateId, String templateParas) throws UnsupportedEncodingException {StringBuilder body = new StringBuilder();appendToBody(body, "from=", sender);appendToBody(body, "&to=", receiver);appendToBody(body, "&templateId=", templateId);appendToBody(body, "&templateParas=", templateParas);return body.toString();}private static void appendToBody(StringBuilder body, String key, String val) throws UnsupportedEncodingException {if (ObjUtil.isNotEmpty(val)) {body.append(key).append(URLEncoder.encode(val, UTF_8));}}
}

http://www.xdnf.cn/news/301573.html

相关文章:

  • c#OdbcDataReader的数据读取
  • Blender 初学者指南 以及模型格式怎么下载
  • FPGA----基于ZYNQ 7020实现petalinux并运行一个程序
  • 赛灵思 XCZU11EG-2FFVC1760I XilinxFPGAZynq UltraScale+ MPSoC EG
  • 探索Hello Robot开源移动操作机器人Stretch 3的新技术亮点与市场定位
  • 在 GitLab 中部署Python定时任务
  • 在与大语言模型交互中的礼貌现象:技术影响、社会行为与文化意义的多维度探讨
  • 告别异步复杂性?JDK 21 虚拟线程让高并发编程重回简单
  • Webview通信系统学习指南
  • 基于C++的IOT网关和平台7:github项目ctGateway设备协议开发指南
  • 点分治解析
  • Spark,配置hadoop集群1
  • Spring AI Alibaba-03- Spring AI + DeepSeek-R1 + ES/Milvus + RAG 智能对话应用开发全流程
  • 从黔西游船侧翻事件看极端天气预警的科技防线——疾风气象大模型如何实现精准防御?
  • 微服务框架中@FeignClient远程调用,请求无法携带问题处理
  • 【工具】解析URL获取实际图片地址下载原始FFHQ图像
  • 如何将本地 Jar 包安装到 Maven 仓库(以 Aspose 为例)
  • 小芯片大战略:Chiplet技术如何重构全球半导体竞争格局?
  • aws平台windows虚拟机扩容
  • Eigen矩阵的平移,旋转,缩放
  • 制造企业PLM系统成本基准:2025年预算分配与资源成本率的5种优化模型
  • AI智能体|扣子(Coze)实战【天气查询插件开发教程】
  • IAA-Net:一种实孔径扫描雷达迭代自适应角超分辨成像方法——论文阅读
  • centos的根目录占了大量空间怎么办
  • nut-list和nut-swipe搭配:nut-cell侧滑定义无法冒泡打开及bug(含代码、案例、截图)
  • 高并发PHP部署演进:从虚拟机到K8S的DevOps实践优化
  • 1. 视频基础知识
  • Java高频面试之并发编程-12
  • 详细教程:如何在vs code里面给普通的HTML搭建局域网服务器给其他设备访问
  • react-14defaultValue(仅在首次渲染时生效)和value(受 React 状态控制)