使用JAVA代码实现发送订阅消息以及模板消息

 今天写了一个商品到货提醒的job任务,具体效果如下

60e2cf561f8a4816aade55ce903dabb0.jpg

这里用到了微信的发送订阅消息,主要代码是这一块的,最后我把发送了消息的订单存到表里,因为是定时任务,大家可不存

发送订阅消息 | 微信开放文档

   /**
     * 微信平台-商品到货通知
     */
    public String uploadArrival(WxOrderArrivalDTO wxOrderArrivalDTO) throws ParseException {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wechatManager.getaccessToken();
        JSONObject body = new JSONObject();
        JSONObject data = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(DateUtil.now());
        data.put("time4",new JSONObject().fluentPut("value",date));
        data.put("character_string5", new JSONObject().fluentPut("value",wxOrderArrivalDTO.getPickupCode()));
        data.put("amount6",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getOrderAmount() + "元"));
        data.put("thing7",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getShopName()) );
        data.put("short_thing8", new JSONObject().fluentPut("value","自提"));
        body.put("data", data);
        body.put("touser", wxOrderArrivalDTO.getOpenId());
        body.put("miniprogram_state", "formal");
        body.put("lang", "zh_CN");
        body.put("template_id", "这里填模板id");
        String result = null;
        try {
            result = HttpUtil.createPost(url).body(body.toJSONString()).execute().body();
            log.info("通知微信平台 订单到货接口返回:" + result);
            OrderPushMsgDTO orderPushMsgDTO = new OrderPushMsgDTO();
            orderPushMsgDTO.setPushMsgId(UUIDUtils.getUUID());
            orderPushMsgDTO.setOrderId(wxOrderArrivalDTO.getOrderId());
            orderPushMsgDTO.setOrderType(CommonKey.CONSTANT_1);
            JSONObject jsonObject = JSON.parseObject(result);
            int errcode = jsonObject.getInteger("errcode");
            orderPushMsgDTO.setErrCode(String.valueOf(errcode));
            orderPushMsgBO.save(orderPushMsgDTO);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
        return result;
    }

这是微信公众号平台申请的模板,其中模板id填到上图中的template_id后面

63ab012c1aed4195aa905d810bf601d1.png

 这是微信官方文档的请求参数示例,主要是data里面的数据key是上图详细内容里的time4,thing7...e47dee90ade74836918ccb5bc95d9da6.png

 然后遇到一个问题,就是给data塞值的时候刚开始采用的是第二种方法,发现没塞进去,用下图框中的写法就可以了

022f5755fea148879ab9f6e71b63000d.png

后面又写了个公众号的,效果如下

这个用法的是微信的模板消息,大致写法都一样,就是tocken要用公众号的tocken,用小程序的tocken会报错48001,还有如果不是一个模板id代码里记得换,不然会报错40037。模板有数据是枚举的,拼接返回消息的时候要对应上

模板消息 | 微信开放文档

public String uploadArrivalOfficialAccountPush(WxOrderArrivalDTO wxOrderArrivalDTO){
        WechatInfoDTO weChatAccessToken = authUtil.getWeChatAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weChatAccessToken.getAccessToken();
        List<OrderItemDTO> itemList= orderItemDao.queryListOrderItemByOrderIdList(Arrays.asList(wxOrderArrivalDTO.getOrderId()));
        List<ShopGoodsDTO> shopGoodsDTOS = this.shopGoodsBo.queryGoodsByIdList(itemList.stream().map(OrderItemDTO::getGoodsId).collect(Collectors.toList()));
        if (ObjectUtil.isNull(shopGoodsDTOS)) {
            return null;
        }
        Map<String, ShopGoodsDTO> shopGoodsDTOMap = shopGoodsDTOS.stream().distinct().collect(Collectors.toMap(ShopGoodsDTO::getGoodsId, Function.identity(), (oldValue, newValue) -> oldValue));
        List<ShopGoodsSpeciInfoDTO> speciInfoList= shopGoodsSpeciInfoBO.queryGoodsSpeciInfoByIdList(itemList.stream().map(OrderItemDTO::getGoodsSpeciId).collect(Collectors.toList()));
        StringBuffer goodNames=new StringBuffer();
        int size = speciInfoList.size();
        for (int i = 0; i < size; i++) {
            ShopGoodsSpeciInfoDTO temp = speciInfoList.get(i);
            String goodsName = shopGoodsDTOMap.get(temp.getGoodsId()).getGoodsName();
            goodNames.append(goodsName);
            if (i < size - 1) {
                goodNames.append("、");
            }
        }
        if(goodNames.toString().length()>20){
            wxOrderArrivalDTO.setItemDesc(goodNames.toString().substring(0,10)+ELLIPSIS_3);
        }else{
            wxOrderArrivalDTO.setItemDesc(goodNames.toString());
        }
        JSONObject body = new JSONObject();
        JSONObject data = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(DateUtil.now());
        data.put("time1",new JSONObject().fluentPut("value",date));
        data.put("thing2",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getItemDesc()));
        data.put("amount3",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getOrderAmount() + "元"));
        data.put("thing4",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getShopName()) );
        data.put("const5", new JSONObject().fluentPut("value",CommonKey.CONSTANT_3.equals(wxOrderArrivalDTO.getDeliveryMethod()) ? "用户自提" : "商家配送"));
        body.put("data", data);
        body.put("url", officialAccountPushUrl);
        body.put("touser", wxOrderArrivalDTO.getOpenId());
        body.put("template_id", "这里填模板id");
        String result = null;
        try {
            result = HttpUtil.createPost(url).body(body.toJSONString()).execute().body();
            log.info("通知微信平台 订单到货接口返回:" + result);
            OrderPushMsgDTO orderPushMsgDTO = new OrderPushMsgDTO();
            orderPushMsgDTO.setPushMsgId(UUIDUtils.getUUID());
            orderPushMsgDTO.setOrderId(wxOrderArrivalDTO.getOrderId());
            orderPushMsgDTO.setOrderType(CommonKey.CONSTANT_1);
            JSONObject jsonObject = JSON.parseObject(result);
            orderPushMsgDTO.setPushType(CommonKey.CONSTANT_2);
            int errcode = jsonObject.getInteger("errcode");
            orderPushMsgDTO.setErrCode(String.valueOf(errcode));
            orderPushMsgBO.save(orderPushMsgDTO);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
        return result;
    }

获取公众号的tocken,要注意是url+json的形式

开始开发 / 获取 Stable Access token

 public WechatInfoDTO getWeChatAccessToken() {
        Map<String,Object> requestUrlParam=new HashMap<String,Object>();
        //appId
        requestUrlParam.put("appid", wechatAppId);
        //appSecret
        requestUrlParam.put("secret", wechatSecret);
        //默认参数
        requestUrlParam.put("grant_type", "client_credential");
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(requestUrlParam);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //发送post请求读取调用微信接口获取accessToken信息
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/stable_token", json);

        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer errcode = jsonObject.getInteger("errcode");
        if (errcode != null && errcode != 0) {
            String errmsg = jsonObject.getString("errmsg");
            log.error(result);
            throw new BizException(ResultCode.FAIL,errmsg);
        }
        return new WechatInfoDTO().setAccessToken(jsonObject.getString("access_token"));
    }

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,这里是一个简单的Java代码示例,可以使用Java语言和Spring框架实现WebSocket结合OPC UA实现订阅并返回数据给前端: ```java // 导入相关依赖 import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem; import org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscription; import org.eclipse.milo.opcua.sdk.client.subscriptions.UaSubscription; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription; import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest; import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateResult; import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Component; import org.springframework.web.socket.WebSocketSession; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class OpcUaWebSocketSubscriptionHandler { // 注入WebSocket消息发送模板 private final SimpMessagingTemplate simpMessagingTemplate; // 保存已订阅的OPC UA监控项 private final List<UaMonitoredItem> monitoredItemList = new ArrayList<>(); // OPC UA连接信息 private final EndpointDescription endpoint; // WebSocket会话对象 private WebSocketSession webSocketSession; // OPC UA订阅对象 private UaSubscription subscription; // 构造函数 public OpcUaWebSocketSubscriptionHandler(SimpMessagingTemplate simpMessagingTemplate) { this.simpMessagingTemplate = simpMessagingTemplate; // TODO: 初始化OPC UA连接信息 } // 处理WebSocket订阅请求 public void handleWebSocketSubscription(WebSocketSession session, String nodeId) { this.webSocketSession = session; // 创建OPC UA订阅 CompletableFuture<UaSubscription> future = createOpcUaSubscription(); future.thenAccept(subscription -> { this.subscription = subscription; // 创建OPC UA监控项 CompletableFuture<MonitoredItemCreateResult> monitoredItemFuture = createOpcUaMonitoredItem(nodeId); monitoredItemFuture.thenAccept(result -> { if (result.getStatusCode().isGood()) { UaMonitoredItem monitoredItem = result.getMonitoredItem(); monitoredItemList.add(monitoredItem); } }); }); } // 处理WebSocket取消订阅请求 public void handleWebSocketUnsubscription(WebSocketSession session, String nodeId) { if (this.webSocketSession != null && webSocketSession.equals(session)) { for (UaMonitoredItem monitoredItem : monitoredItemList) { if (monitoredItem.getReadValueId().getNodeId().getIdentifier().toString().equals(nodeId)) { subscription.removeItem(monitoredItem); monitoredItemList.remove(monitoredItem); break; } } } } // 创建OPC UA订阅 private CompletableFuture<UaSubscription> createOpcUaSubscription() { CompletableFuture<UaSubscription> future = new CompletableFuture<>(); // 创建OPC UA订阅 OpcUaSubscription subscription = new OpcUaSubscription(this.endpoint.getClient(), 1000.0); subscription.addNotificationListener(this::onSubscriptionValue); subscription.addStatusListener(this::onSubscriptionStatusChanged); subscription.setPublishingEnabled(true); subscription.setLifetimeCount(1000); subscription.setMaxKeepAliveCount(10); subscription.setPriority((byte) 0); // 启动OPC UA订阅 CompletableFuture<Void> future1 = subscription.connect(); future1.thenAccept(v -> { if (subscription.getSession().isPresent()) { future.complete(subscription); } }); return future; } // 创建OPC UA监控项 private CompletableFuture<MonitoredItemCreateResult> createOpcUaMonitoredItem(String nodeId) { CompletableFuture<MonitoredItemCreateResult> future = new CompletableFuture<>(); // 创建OPC UA监控项 ReadValueId readValueId = new ReadValueId( new NodeId(0, nodeId), AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE); MonitoredItemCreateRequest request = new MonitoredItemCreateRequest( readValueId, MonitoringMode.Reporting, new MonitoringParameters( 0.0, 10.0, null, 10, true ) ); // 添加OPC UA监控项 CompletableFuture<List<MonitoredItemCreateResult>> future1 = subscription.createMonitoredItems( TimestampsToReturn.Both, Lists.newArrayList(request) ); future1.thenAccept(resultList -> { if (resultList.size() > 0) { future.complete(resultList.get(0)); } }); return future; } // 处理OPC UA订阅值变化事件 private void onSubscriptionValue(UaMonitoredItem item, DataValue value) { String nodeId = item.getReadValueId().getNodeId().getIdentifier().toString(); String message = value.getValue().getValue().toString(); simpMessagingTemplate.convertAndSendToUser( webSocketSession.getId(), "/topic/opcua/value/" + nodeId, message ); } // 处理OPC UA订阅状态变化事件 private void onSubscriptionStatusChanged(UaSubscription subscription, StatusCode statusCode) { if (!statusCode.isGood()) { simpMessagingTemplate.convertAndSendToUser( webSocketSession.getId(), "/topic/opcua/status", "OPC UA subscription status changed: " + statusCode ); } } } ``` 这段代码实现了WebSocket结合OPC UA实现订阅,并将数据发送给前端的功能。在代码中,我们使用了Spring框架的SimpMessagingTemplate组件,用于发送WebSocket消息。我们通过创建UaMonitoredItem对象实现对OPC UA变量值的监控,并在变量值变化时,通过SimpMessagingTemplate将变量值发送给前端。同时,我们也实现了处理WebSocket取消订阅请求的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑看夕阳染红天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值