• Stars
    star
    1,233
  • Rank 36,477 (Top 0.8 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 3 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

微信推送服务Server酱的开源替代。通过企业微信向微信推送消息的配置文档、直推函数和可自行搭建的在线服务代码。

Wecom酱

通过企业微信向微信推送消息的解决方案。包括:

  1. 配置说明(本页下方)
  2. 推送函数(支持多种语言,见本页下方)
  3. 自行搭建的在线服务源码
    1. PHP版搭建说明
    2. Go版说明
    3. Go适配华为函数工作流版本
    4. 阿里云云函数搭建说明
    5. 腾讯云云函数搭建说明 ⚠️ 2022年5月23日起最低月消费9.9,因此不推荐了
    6. 百度智能云函数搭建说明

🎈 本项目属于方糖推送生态。该生态包含项目如下:

  • Server酱Turbo:支持企业微信、微信服务号、钉钉、飞书群机器人等多通道的在线服务,无需搭建直接使用,每天有免费额度
  • Wecom酱:通过企业微信推送消息到微信的消息推送函数和在线服务方案,开源免费,可自己搭建。支持多语言。
  • PushDeer:可自行搭建的、无需安装APP的开源推送方案。同时也提供安装APP的降级方案给低版本/没有快应用的系统。支持作为Server酱的通道进行推送,所有支持Server酱的软件和插件都能直接整合PushDeer。

企业微信应用消息配置说明

优点:

  1. 一次配置,持续使用
  2. 配置好以后,只需要微信就能收消息,不再需要安装企业微信客户端

PS:消息接口无需认证即可使用,个人用微信就可以注册

具体操作

第一步,注册企业

用电脑打开企业微信官网,注册一个企业

第二步,创建应用

注册成功后,点「管理企业」进入管理界面,选择「应用管理」 → 「自建」 → 「创建应用」

应用名称填入「Server酱」,应用logo到这里下载,可见范围选择公司名。

创建完成后进入应用详情页,可以得到应用ID( agentid )①,应用Secret( secret )②。

注意:secret推送到手机端时,只能在企业微信客户端中查看。

第三步,添加可信IP

2022年6月20日之后创建的应用,需要额外配置可信IP。

在「应用详情页」的最下方,开发者接口分类中,找到「企业可信IP」,点击「配置」,并填入服务器IP即可。

注意,如果你使用云函数等公用IP的云服务,可能需要在(云函数或其他服务的)设置界面中打开「固定公网IP」来获得一个独立的IP。否则有可能报「第三方服务IP」错误。

第四步,获取企业ID

进入「我的企业」页面,拉到最下边,可以看到企业ID③,复制并填到上方。

推送UID直接填 @all ,推送给公司全员。

第五步,推送消息到微信

进入「我的企业」 → 「微信插件」,拉到下边扫描二维码,关注以后即可收到推送的消息。

PS:如果出现接口请求正常,企业微信接受消息正常,个人微信无法收到消息的情况:

  1. 进入「我的企业」 → 「微信插件」,拉到最下方,勾选 “允许成员在微信插件中接收和回复聊天消息”

  2. 在企业微信客户端 「我」 → 「设置」 → 「新消息通知」中关闭 “仅在企业微信中接受消息” 限制条件

第六步,通过以下函数发送消息:

PS:为使用方便,以下函数没有对 access_token 进行缓存。对于个人低频调用已经够用。带缓存的实现可查看 index.php 中的示例代码(依赖Redis实现)。

PHP版:

function send_to_wecom($text, $wecom_cid, $wecom_aid, $wecom_secret,  $wecom_touid = '@all')
{
    $info = @json_decode(file_get_contents("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".urlencode($wecom_cid)."&corpsecret=".urlencode($wecom_secret)), true);
                
    if ($info && isset($info['access_token']) && strlen($info['access_token']) > 0) {
        $access_token = $info['access_token'];
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.urlencode($access_token);
        $data = new \stdClass();
        $data->touser = $wecom_touid;
        $data->agentid = $wecom_aid;
        $data->msgtype = "text";
        $data->text = ["content"=> $text];
        $data->duplicate_check_interval = 600;

        $data_json = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        return $response;
    }
    return false;
}

使用实例:

$ret = send_to_wecom("推送测试\r\n测试换行", "企业ID③", "应用ID①", "应用secret②");
print_r( $ret );

PYTHON版:

import json,requests,base64
def send_to_wecom(text,wecom_cid,wecom_aid,wecom_secret,wecom_touid='@all'):
    get_token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={wecom_cid}&corpsecret={wecom_secret}"
    response = requests.get(get_token_url).content
    access_token = json.loads(response).get('access_token')
    if access_token and len(access_token) > 0:
        send_msg_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
        data = {
            "touser":wecom_touid,
            "agentid":wecom_aid,
            "msgtype":"text",
            "text":{
                "content":text
            },
            "duplicate_check_interval":600
        }
        response = requests.post(send_msg_url,data=json.dumps(data)).content
        return response
    else:
        return False

def send_to_wecom_image(base64_content,wecom_cid,wecom_aid,wecom_secret,wecom_touid='@all'):
    get_token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={wecom_cid}&corpsecret={wecom_secret}"
    response = requests.get(get_token_url).content
    access_token = json.loads(response).get('access_token')
    if access_token and len(access_token) > 0:
        upload_url = f'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image'
        upload_response = requests.post(upload_url, files={
            "picture": base64.b64decode(base64_content)
        }).json()
        if "media_id" in upload_response:
            media_id = upload_response['media_id']
        else:
            return False

        send_msg_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
        data = {
            "touser":wecom_touid,
            "agentid":wecom_aid,
            "msgtype":"image",
            "image":{
                "media_id": media_id
            },
            "duplicate_check_interval":600
        }
        response = requests.post(send_msg_url,data=json.dumps(data)).content
        return response
    else:
        return False

def send_to_wecom_markdown(text,wecom_cid,wecom_aid,wecom_secret,wecom_touid='@all'):
    get_token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={wecom_cid}&corpsecret={wecom_secret}"
    response = requests.get(get_token_url).content
    access_token = json.loads(response).get('access_token')
    if access_token and len(access_token) > 0:
        send_msg_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
        data = {
            "touser":wecom_touid,
            "agentid":wecom_aid,
            "msgtype":"markdown",
            "markdown":{
                "content":text
            },
            "duplicate_check_interval":600
        }
        response = requests.post(send_msg_url,data=json.dumps(data)).content
        return response
    else:
        return False

使用实例:

ret = send_to_wecom("推送测试\r\n测试换行", "企业ID③", "应用ID①", "应用secret②");
print( ret );
ret = send_to_wecom('<a href="https://www.github.com/">文本中支持超链接</a>', "企业ID③", "应用ID①", "应用secret②");
print( ret );
ret = send_to_wecom_image("此处填写图片Base64", "企业ID③", "应用ID①", "应用secret②");
print( ret );
ret = send_to_wecom_markdown("**Markdown 内容**", "企业ID③", "应用ID①", "应用secret②");
print( ret );

TypeScript 版:

import request from 'superagent'

async function sendToWecom(body: {
  text: string
  wecomCId: string
  wecomSecret: string
  wecomAgentId: string
  wecomTouid?: string
}): Promise<{ errcode: number; errmsg: string; invaliduser: string }> {
  body.wecomTouid = body.wecomTouid ?? '@all'
  const getTokenUrl = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${body.wecomCId}&corpsecret=${body.wecomSecret}`
  const getTokenRes = await request.get(getTokenUrl)
  const accessToken = getTokenRes.body.access_token
  if (accessToken?.length <= 0) {
    throw new Error('获取 accessToken 失败')
  }
  const sendMsgUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accessToken}`
  const sendMsgRes = await request.post(sendMsgUrl).send({
    touser: body.wecomTouid,
    agentid: body.wecomAgentId,
    msgtype: 'text',
    text: {
      content: body.text,
    },
    duplicate_check_interval: 600,
  })
  return sendMsgRes.body
}

使用实例:

sendToWecom({
  text: '推送测试\r\n测试换行',
  wecomAgentId: '应用ID①',
  wecomSecret: '应用secret②',
  wecomCId: '企业ID③',
})
  .then((res) => {
    console.log(res)
  })
  .catch((err) => {
    console.log(err)
  })

.NET Core 版:

using System;
using RestSharp;
using Newtonsoft.Json;
namespace WeCom.Demo
{
    class WeCom
    {   
        public  string SendToWeCom(
            string text,// 推送消息
            string weComCId,// 企业Id①
            string weComSecret,// 应用secret②
            string weComAId,// 应用ID③
            string weComTouId = "@all")
        {
            // 获取Token
            string getTokenUrl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={weComCId}&corpsecret={weComSecret}";
            string token = JsonConvert
            .DeserializeObject<dynamic>(new RestClient(getTokenUrl)
            .Get(new RestRequest()).Content).access_token;
            System.Console.WriteLine(token);
            if (!String.IsNullOrWhiteSpace(token))
            {
                var request = new RestRequest();
                var client = new RestClient($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}");
                var data = new
                {
                    touser = weComTouId,
                    agentid = weComAId,
                    msgtype = "text",
                    text = new
                    {
                        content = text
                    },
                    duplicate_check_interval = 600
                };
                string serJson = JsonConvert.SerializeObject(data);
                System.Console.WriteLine(serJson);
                request.Method = Method.POST;
                request.AddHeader("Accept", "application/json");
                request.Parameters.Clear();
                request.AddParameter("application/json", serJson, ParameterType.RequestBody);
                return client.Execute(request).Content;
            }
            return "-1";
        }
}

使用实例:

   static void Main(string[] args)
        {   // 测试
            Console.Write(new WeCom().SendToWeCom(
            "msginfo",
            "企业Id①"
            , "应用secret②",
            "应用ID③"
            ));
        }

    }

其他版本的函数可参照上边的逻辑自行编写,欢迎PR。

发送图片、卡片、文件或 Markdown 消息的高级用法见 企业微信API

More Repositories

1

howto-make-more-money

程序员如何优雅的挣零花钱,2.0版,升级为小书了。Most of this not work outside China , so no English translate
PHP
16,190
star
2

lean-side-bussiness

精益副业:程序员如何优雅地做副业
8,305
star
3

pushdeer

开放源码的无App推送服务,iOS14+扫码即用。亦支持快应用/iOS和Mac客户端、Android客户端、自制设备
C
4,353
star
4

one-person-businesses-methodology

一人公司方法论
3,220
star
5

stack-roadmap

方糖全栈路线图2023,为「从螺丝钉到一人企业」补全技能栈
PHP
3,063
star
6

CookieCloud

CookieCloud是一个和自架服务器同步浏览器Cookie和LocalStorage的小工具,支持端对端加密,可设定同步时间间隔。本仓库包含了插件和服务器端源码。CookieCloud is a small tool for synchronizing browser cookies and LocalStorage with a self-hosted server. It supports end-to-end encryption and allows for setting the synchronization interval. This repository contains both the plugin and the server-side source code
JavaScript
1,581
star
7

checkchan-dist

Check酱:监测网页内容变化,并发送异动到微信。亦支持http status、json和rss监测。配合自架云端,关电脑后也能运行。
JavaScript
1,532
star
8

openai-api-proxy

一行Docker命令部署的 OpenAI/GPT API代理,支持SSE流式返回、腾讯云函数 。Simple proxy for OpenAi api via a one-line docker command
JavaScript
1,450
star
9

openai-gpt-dev-notes-for-cn-developer

如何快速开发一个OpenAI/GPT应用:国内开发者笔记
Shell
1,403
star
10

docker2saas

An open source tool that lets you create a SaaS website from docker images in 10 minutes.
PHP
765
star
11

chatchan-dist

Chat酱独立部署版,docker方案自带代理
Dockerfile
729
star
12

catgate

CatGate is a small crawler framework based on Chrome extension . CatGate是一个基于浏览器插件的数据抓取工具。做成浏览器插件无需模拟登入,能最真实的模仿用户行为和特征。
Vue
673
star
13

TeamToy

企业协同办公工具TeamToy2(多人TODO版)官方Git源
PHP
662
star
14

LazyPHP

轻框架。包含一个前端控制器,20个常用函数和用于页面布局的Layout系统,10分钟即可学会。LP采用BSD开源协议,在代码内保留框架名即可随意商用。
PHP
573
star
15

rsspush

监测RSS变动,并发送最新内容到微信、Webhook 和 Telegram, Discord, Slack, Amazon SNS, Gotify 等数十个消息通道。
499
star
16

telechan

message api for telegram bot 可供多人发送消息的 telegram 机器人 api , 类似server酱的开源实现
TypeScript
414
star
17

not-only-fans

an open source, self-hosted digital content subscription platform like `onlyfans.com` with cryptocurrency payment
HTML
356
star
18

career-guide-for-cs-graduate

计算机系应届生求职指北
316
star
19

LazyPHP4

LazyPHP4 , an API first framework for php developer
PHP
315
star
20

MemberPrism2

open source alternative to memberstack / memberspace , but with both front and backend member-only content protection
PHP
273
star
21

http-t-shirts

Open source http status code T shirt · http状态码系列T恤设计稿
266
star
22

tumblr-like-exporter

Download tumblr photos you liked , or others liked . Or even images in your blog . It supports videos now , see README to enable it
PHP
262
star
23

LazyRest4

基于Web界面的Rest风格API生成器For LazyPHP4
PHP
244
star
24

botchan

基于微信测试号的ChatBot,对接OpenAI API
JavaScript
242
star
25

lianmilite

莲米粒是一个基于PHP+MySQL+微信小程序技术栈的、拥有用户登入、发布、修改、删除和转发信息、以及私信聊天模块的信息流应用。
PHP
233
star
26

deepgpt-dist

DeepGPT,类agentGPT/AutoGPT 工具,支持 api2d / 和自定义 openai key。此为静态网页独立部署版,部署方便
JavaScript
227
star
27

book-by-ai

Generate high-quality books with AI
JavaScript
216
star
28

TeamToy-Pocket

TeamToy是跨平台的团队TODO应用,官网 TeamToy.net。 TeamToyPocket是其移动客户端。本项目采用GPLV2协议,本分支代码用于在新浪移动云上直接打包。如果自行用PhoneGap打包,请将代码中<phonegap></phonegap>换成phonegap.js的路径。
JavaScript
203
star
29

LazyREST

可通过Web配置的REST Server,采用GPLV2授权
PHP
193
star
30

gpt-bat

GPT长文本批处理工具,Batch Processing tools for GPT
JavaScript
184
star
31

LazyAudioBook

将 txt 文件生成语音书。
PHP
167
star
32

flowdeer-dist

可用于深度思考和复杂流程的AI工具
163
star
33

LeanBase

143
star
34

aiapi

A Claude-driven, OpenAI specification-compliant API, free
135
star
35

onlytech-javascript-info

纯粹技术免费课计划·现代JavaScript 教程
112
star
36

timetodo-server

remote server for timetodo
PHP
108
star
37

windrecorder

JavaScript
103
star
38

rumenqi

从入门到放弃系列周边补全计划
98
star
39

api2d-js

OpenAI/Api2d pure js sdk 无需node后端直接在浏览器中运行,支持SSE流式输出
JavaScript
90
star
40

fangPHP

fangPHP is a docker based development env with php7 mysql redis and livereload
PHP
84
star
41

any2api

A framework( or a tool? ) that turns any website into an API
JavaScript
81
star
42

h2webreader

h2book web reader
JavaScript
78
star
43

awesome-checkchan

Check酱任务分享清单
76
star
44

windmark-practice

采用 windmark 编写的视频的源文件
74
star
45

h2reader-host

方糖小剧场Web阅读器和上传网站
JavaScript
72
star
46

Simple-Weibo

PS: 这个方案有些过时了,建议用新方案 https://github.com/qhm123/tinybo open source phonegap weibo client demo 。想要更多功能的同学自己写嘛,别偷懒哈。
JavaScript
70
star
47

url2pdf

url2pdf docker image based on wkhtmltopdf with Chinese support.
PHP
68
star
48

code-tattoo

语言纹身贴纸图案库
60
star
49

GPT4Company

Gpt4Company is a request forwarder used to prevent Samsung-style leaks. Gpt4Company 是一个用来避免三星式泄密的请求转发器
JavaScript
57
star
50

ffonline

video creating in browser
JavaScript
57
star
51

LazyBoardExt

定时采集数据并发送到指定接口的Chrome扩展机器人🤖
JavaScript
54
star
52

nCoV-push

nCoV疫情实时播报推送脚本。数据基于丁香园。
PHP
53
star
53

Wechat-Wordpress-Search

a wordpress plugin allowed user search blogs in wechat app
PHP
52
star
54

MoDocker

modo动漫私有云(modo.moe)的Docker构建用文件。
PHP
40
star
55

ask-gpt-download

通过GPT向微博账号提问
39
star
56

WindChat

A React Chatbot starter with highly customizable styles can be achieved through TailwindCSS. 可以通过 TailwindCSS 高度定制样式的 React Chatbot starter。
JavaScript
36
star
57

fo-pay

基于加密稳定币 FOUSDT 的 WordPress 付费阅读插件。
PHP
33
star
58

Fangtang-Chrome-Starter-Kit

Starter Kit for chrome extension based on Vue2 and ElementUI
JavaScript
33
star
59

serverchan-demo

Server酱多语言调用实例
Java
31
star
60

vue-starter

JavaScript
27
star
61

fangtangtree

方糖知识树
26
star
62

nowboard

基于SAE Channel服务的实时信息流展板。通过微博帐号登入、可聊天;支持API发布信息,可用于服务器调试信息、错误信息展示。
PHP
26
star
63

TeamToy-Plugins

TeamToy插件目录
PHP
24
star
64

LazyExtKit

a simple chrome extension startkit
JavaScript
24
star
65

github-action-server-chan

TypeScript
23
star
66

MetaToy2

通用命令行和可视化代码生成工具
EJS
19
star
67

WeiboList

微博上活跃的技术帐号整理
19
star
68

easy-starter2

react + mobx + react-router v4 + react-next-i18n starter for create-react-app 2.x
JavaScript
17
star
69

fangtangCV-react-native

react native demo
JavaScript
16
star
70

serverchan-wordpress-comments-notice

Server酱WordPress博客评论微信通知插件
PHP
16
star
71

easy-starter

一个整合了 react 、 react-router v4 和 mobx 的简单起始项目脚手架
JavaScript
15
star
72

LazyBot

一些基于 robo.li 的日常自动化/半自动化脚本
PHP
15
star
73

one-person-businesses-methodology-v2

用AI撰写的一本小书
Shell
14
star
74

teamtoy-mina-demo

一个调用TeamToy API 的微信小程序 Demo
JavaScript
14
star
75

CubismWebSamples-with-lip-sync

TypeScript
14
star
76

fullstack-learnning-map

全栈创业者(fullstack-creator)的知识地图
13
star
77

fangtangCV

PHP
12
star
78

2dstudio-dist

使用 API2D Key 的 Stable Studio,独立部署版
HTML
12
star
79

Aoi

LazyPHP3的看板娘,能帮你自动创建模板,Action和测试。
PHP
12
star
80

xf-tts-sdk

php & node sdk for xunfei tts websocket api
JavaScript
10
star
81

easychen.github.com

8
star
82

tcp

tcp包介绍网站
CSS
8
star
83

autoplay-web-specification

自播放网页规范 specification of autoplay web
7
star
84

imgShare

为文章中的图片添加鼠标浮动时分享到微博的链接。封装自 国内首家互联网人才拍卖网站 JobDeer.com
JavaScript
6
star
85

fangtangGif

方糖动图生成器
6
star
86

telegram-bot-api-proxy

express app for forwarding request to api.telegram.org
JavaScript
4
star
87

GameDemo

DemoGame for FE courses , Just a hosting , not open source project
4
star
88

easychen.github.io

HTML
4
star
89

book-by-ai-demo-book

3
star
90

LitePHP

Simple version of LazyPHP in one file
PHP
3
star
91

wordpress-local-dev-env

3
star
92

serverchan-e2e-demo

Server酱端对端加密函数和DEMO
2
star
93

fangCV

PHP
2
star
94

easychen

2
star
95

cubeslam

Automatically exported from code.google.com/p/cubeslam
JavaScript
2
star
96

TeamToy-Language-Files

translate teamtoy to other languages
PHP
2
star
97

fxd

Flow eXtension Define,它是一个被设计用于工作流(尤其是AI和自动化工作流)扩展的规范。"Flow eXtension Define" is a specification designed for extending workflows, especially AI and automation workflows.
JavaScript
2
star
98

bluesky-wave

Bluesky bulk follow tool
JavaScript
2
star
99

m5dash

Python
1
star
100

2d-ai-chatbot

TypeScript
1
star