美文网首页
c#/js/shell企业微信推送办法

c#/js/shell企业微信推送办法

作者: 吉凶以情迁 | 来源:发表于2023-03-29 14:14 被阅读0次
  public class MyHttpUtil
    {
        public static string sendPostJSON(string url, string json)
        {

            /*        var client = new HttpClient();
                    var request = new HttpRequestMessage(HttpMethod.Post, url);
                    request.Content = new StringContent(json, Encoding.UTF8, "application/json");

                    var response =  client.SendAsync(request);
                    var responseContent =  response.Content.ReadAsStringAsync();
        */

            using (var client = new HttpClient())
            {
                //var data = new { name = "John Doe", age = 30 };
                //Newtonsoft.Json.JsonConvert.SerializeObject(data)
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
                //var responseContent = response.Result.Content.ReadAsStringAsync();
                return response;
            }



        }

        public   string sendGet(string url)
        {

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(url);
                var responseContent =   response.Result.Content.ReadAsStringAsync().Result;
                return responseContent;
            }


        }




    }
    using (WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.UTF8;
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                    String url = @$"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={secret}";




                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    String result = encode.GetString(pageData);
                    if (!result.Contains("{"))
                    {
                        return result;
                    }
                    JObject obj = JObject.Parse(result);
                    if (!obj["errcode"].ToString().Equals("0"))
                    {
                        return result;

                    }
                    string access_token = obj["access_token"].ToString();// jobj["access_token"];
                    JObject POST = new JObject();
                    POST.Add("touser", "");
                    POST.Add("agentid", agent_id);
                    POST.Add("msgtype", "");
                    JObject contentJOBJ = new JObject();
                    contentJOBJ.Add("content", content);
                    POST.Add("text", contentJOBJ);
                    return MyHttpUtil.sendPostJSON($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}", POST.ToString());
                }

登录申请企业微信https://work.weixin.qq.com
在我的企业选项卡得到企业ID 也就是接口地址的(corp_id)
在应用管理界面创建一个应用
在这个创建的应用管理界面找到(AgentId ) (Secret)
在这个创建的应用管理界面填写可信域名 (备案的域名)进行认证
在这个创建的应用管理界面填写企业可信IP
为推送接口 webapi所在ip,也就是谁发起http请求的,那么就填写谁

推送要指定人要么是@all要么具体企业的用户id否则会出错

   string access_token = obj["access_token"].ToString();// jobj["access_token"];
                    JObject POST = new JObject();
                    POST.Add("touser", "@all");
                    //"touser" : '@all',//意思是发给所有人
                    POST.Add("agentid", agent_id);
                    POST.Add("is_to_all", true);
                    POST.Add("msgtype", "text");
                    JObject contentJOBJ = new JObject();
                    contentJOBJ.Add("content", content);
                    POST.Add("text", contentJOBJ);
                    return MyHttpUtil.sendPostJSON($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}", POST.ToString());

参考资料
https://juejin.cn/post/7184359646869520445
https://zhuanlan.zhihu.com/p/460215635
https://blog.csdn.net/m0_64130892/article/details/128533639

最后整了一个方便测试的 sh shell脚本

image.png
#!/bin/bash

# 从用户输入中获取参数
read -p "Corp ID: " corp_id
read -p "Secret: " secret
read -p "Agent ID: " agent_id
read -p "To User: " touser
read -p "Content: " content

# 发送 GET 请求获取 access_token
url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corp_id&corpsecret=$secret"
result=$(curl -s "$url")
if [[ $result != *{* ]]; then
    echo "Error: $result" >&2
    read -p "Press any key to exit." -n1 -s
    exit 1
fi
errcode=$(echo "$result" | sed -n 's/.*"errcode":[[:space:]]*\([0-9]*\).*/\1/p')
if [[ $errcode != "0" ]]; then
    errmsg=$(echo "$result" | sed -n 's/.*"errmsg":[[:space:]]*"\([^"]*\)".*/\1/p')
    echo "Error: $errmsg" >&2
    read -p "Press any key to exit." -n1 -s
    exit 1
fi
access_token=$(echo "$result" | sed -n 's/.*"access_token":[[:space:]]*"\([^"]*\)".*/\1/p')

# 构造 POST 数据并发送请求
post_data='{
    "touser": "'"$touser"'",
    "agentid": '"$agent_id"',
    "is_to_all": true,
    "msgtype": "text",
    "text": {
        "content": "'"$content"'"
    }
}'
post_url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token"
result=$(curl -s -H "Content-Type: application/json" -X POST -d "$post_data" "$post_url")
if [[ $result != *{* ]]; then
    echo "Error: $result" >&2
    read -p "Press any key to exit." -n1 -s
    exit 1
fi
errcode=$(echo "$result" | sed -n 's/.*"errcode":[[:space:]]*\([0-9]*\).*/\1/p')
if [[ $errcode != "0" ]]; then
    errmsg=$(echo "$result" | sed -n 's/.*"errmsg":[[:space:]]*"\([^"]*\)".*/\1/p')
    echo "Error: $errmsg" >&2
    read -p "Press any key to exit." -n1 -s
    exit 1
fi

# 输出成功信息,并将结果通过 alert 和 console.info 提示给用户
echo "Message sent successfully."
echo "alert('Message sent successfully.');console.info('$result');"


还整了一个html的请求 但是这个跨域请求需要浏览器插件强制跳过

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>POST Request Example</title>
</head>
<body>
  <form id="sendMessageForm">
    <label for="corp_id">Corp ID:</label>
    <input type="text" id="corp_id" name="corp_id" required><br>

    <label for="secret">Secret:</label>
    <input type="text" id="secret" name="secret" required><br>

    <label for="agent_id">Agent ID:</label>
    <input type="text" id="agent_id" name="agent_id" required><br>

    <label for="touser">To User:</label>
    <input type="text" id="touser" name="touser" required><br>

    <label for="content">Content:</label>
    <input type="text" id="content" name="content" required><br>

    <input type="submit" value="Send Message">
  </form>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      $("#sendMessageForm").submit(function(event) {
        event.preventDefault();

        var corp_id = $("#corp_id").val();
        var secret = $("#secret").val();
        var agent_id = $("#agent_id").val();
        var touser = $("#touser").val();
        var content = $("#content").val();

        var getTokenUrl = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corp_id}&corpsecret=${secret}`;
        $.get(getTokenUrl, function(response) {
          if (response.errcode !== 0) {
            console.error(response);
            alert("Error: " + response.errmsg);
          } else {
            var access_token = response.access_token;

            var sendMessageUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`;
            var data = {
              touser: touser,
              agentid: agent_id,
              is_to_all: false,
              msgtype: 'text',
              text: {
                content: content
              }
            };
            $.ajax({
              url: sendMessageUrl,
              type: "POST",
              data: JSON.stringify(data),
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(response) {
                console.log(response);
                alert("Message sent successfully.");
              },
              error: function(xhr, status, error) {
                console.error(status + " - " + error);
                alert("Error: " + error);
              }
            });
          }
        });
      });
    });
  </script>
</body>
</html>

相关文章

网友评论

      本文标题:c#/js/shell企业微信推送办法

      本文链接:https://www.haomeiwen.com/subject/dnqkrdtx.html