HTML中利用JS实现企业微信分享会话消息sendChatMessage

报签名错误,权限错误。错误代码忘记了。。。。。。。

企业微信给客户发消息,没有直接的接口,只能通过分享消息到当前会话来实现

分享消息到当前会话 - 接口文档 - 企业微信开发者中心

那么根据文档就要去实现相关的接口,我这里没有用VUE来实现,(网上满满的),后端我用的wxjava,感谢大佬开源的好用的微信sdk.WxJava: 微信开发 Java SDK,支持微信支付、开放平台、公众号、视频号、企业微信、小程序等的后端开发,记得关注公众号及时接受版本更新信息,以及加入微信群进行深入讨论

参考例子(拿来改改都能用):

weixin-java-cp-demo: 企业微信 后端Demo,基于 WxJava 和 Spring Boot 实现

先贴html代码 再贴java

我这里用js在HTML实现该功能。先贴代码,再讲遇到的问题。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业微信分享消息示例</title>
    <script src="https://wwcdn.weixin.qq.com/node/open/js/wecom-jssdk-2.0.2.js"></script> <!-- 替换为实际的 SDK URL -->
</head>
<body>

<button id="sendMessageBtn">发送消息到当前会话</button>

<script>
    // 获取签名配置
    function getJsConfig() {
        return fetch('https://weXXXg.com/wx/cp/js/wwa6927329aXXc372/1000003/getAgentConf', {
            method: 'POST', // Change to POST request
            headers: {
                'Content-Type': 'application/json' // Set the content type to JSON
            },
            body: JSON.stringify({"uri":"https://wechxxx.com/wx/cp/welcome"}) // 后端接到用就可以,我的是写死的等会贴代码
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Assuming the returned data structure contains the following fields
                return {
                    corpId: data.appId, // 企业微信的corpID
                    timestamp: data.timestamp, // 生成签名的时间戳
                    nonceStr: data.nonceStr, // 生成签名的随机串
                    signature: data.signature // 签名
                };
            });
    }

    // 配置企业微信
    function wxConfig() {
        getJsConfig().then(function(config) {
            ww.register({
                corpId: config.corpId,
                agentId: "1000003", // 从后端获取
                jsApiList: ['sendChatMessage'], // 必填,需要使用的
                // getConfigSignature: function() {
                //     alert("config:" + JSON.stringify(config))
                //     return { timestamp: config.timestamp, nonceStr: config.nonceStr, signature: config.signature };
                // },
                getAgentConfigSignature: function() {
                    alert("agent:" + JSON.stringify(config))
                    return { timestamp: config.timestamp, nonceStr: config.nonceStr, signature: config.signature };
                },
                // onConfigSuccess: function (result){
                //     alert("配置成功:", result)
                // },
                // onConfigFail: function (res){
                //     alert("配置失败:", res)
                // },
                onAgentConfigSuccess: function(result) {
                    alert("agent成功:", result)
                    console.log("配置成功:", result);
                },
                onAgentConfigFail: function(result) {
                    alert("agent配置失败: " + JSON.stringify(result));
                },
            });

        }).catch(function(error) {
            console.error("获取签名配置失败:", error);
        });
    }

    // 发送消息到当前会话
    function sendMessage() {
        // ww.checkJsApi({
        //     jsApiList: ['getContext','getExternalContact', 'sendChatMessage']
        // })
        var params = {
            msgtype: 'text',
            enterChat: true, //为true时表示发送完成之后顺便进入会话,仅移动端3.1.10及以上版本支持该字段
            text: {
                content: '你好'
            },
            success: function(result) {
                console.log("消息发送成功:", result);
            },
            fail: function(result) {
                alert("消息发送失败: " + JSON.stringify(result));
            }
        };

        ww.sendChatMessage(params);
        // ww.sendChatMessage({
        //     msgtype: 'text',
        //     text: {
        //         content: '你好'
        //     }
        // });
    }

    document.getElementById("sendMessageBtn").addEventListener("click", function() {
        sendMessage();
    });

    // 初始化配置
    wxConfig(); // 不再需要传递 appid,直接获取配置
</script>

</body>
</html>

分享应用上的消息,是个应用。那么就要完善应用的配置。登录企业微信后台,找到应用管理。

我这里分享应用的消息,不知道为什么网上很多

getConfigSignature和
getAgentConfigSignature一起写的。给我造成了很大困扰,我和应用挂钩,只留agent的,另一个干掉就可以。另一个带着也可以,在应用里getConfigSignature不会走,那个wxjava提供的demo里是
getConfigSignature,我需要的是getAgentConfigSignature,这个工具类封装的很完美,我复制了了一份只改url的path部分贴代码(URI一定要有  签名用的 不然报错哦 我这里写死):
@PostMapping("/getAgentConf")
    public Map getAgentConf(
        @PathVariable String corpId,
        @PathVariable Integer agentId,
        @RequestBody String uri) throws WxErrorException {

//        uri = JsonUtils.parseArrayMap(uri).getFirst().get("uri") + "";
        final WxCpService wxCpService = WxCpConfiguration.getCpService(corpId, agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置,请核实!", agentId));
        }
        uri = "https://wxxxxxang.com/wx/cp/welcome";

        WxCpAgentJsapiSignature wxCpAgentJsapiSignature = wxCpService.createAgentJsapiSignature(uri);
        String signature = wxCpAgentJsapiSignature.getSignature();
        String nonceStr = wxCpAgentJsapiSignature.getNonceStr();
        long timestamp = wxCpAgentJsapiSignature.getTimestamp();

        Map res = new HashMap<String, String>();
        res.put("appId", corpId); // 必填,企业微信的corpID
        res.put("timestamp", timestamp); // 必填,生成签名的时间戳
        res.put("nonceStr", nonceStr); // 必填,生成签名的随机串
        res.put("signature", signature); // 必填,签名,见 附录-JS-SDK使用权限签名算法
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值