A solution to push messages to WeChat through Enterprise WeChat. include:
advantage:
PS: The messaging interface can be used without authentication. Individuals can register using WeChat.
Use your computer to open the official corporate WeChat website and register a company
After successful registration, click "Manage Enterprise" to enter the management interface, select "Application Management" → "Self-Build" → "Create Application"
Fill in "Server Sauce" for the application name, download the application logo here, and select the company name for the visible range.
After the creation is completed, enter the application details page and you can get the application ID ( agentid
)① and the application Secret ( secret
)②.
Note: When secret
is pushed to the mobile phone, it can only be viewed in企业微信客户端
.
Applications created after June 20, 2022 need to configure additional trusted IPs.
At the bottom of the "Application Details Page", in the Developer Interface category, find "Enterprise Trusted IP", click "Configure" and fill in the server IP.
Note that if you use a public IP cloud service such as Cloud Function, you may need to turn on "Fixed Public IP" in the settings interface (of Cloud Function or other services) to obtain an independent IP. Otherwise, a "Third Party Service IP" error may be reported.
Enter the "My Business" page, scroll to the bottom, you can see the business ID ③, copy and fill it to the top.
To push the UID, fill in @all
directly and push it to all employees in the company.
Enter "My Business" → "WeChat Plug-in", scroll down and scan the QR code, and follow it to receive push messages.
PS: If接口请求正常,企业微信接受消息正常,个人微信无法收到消息
:
Go to "My Business" → "WeChat Plug-in", scroll to the bottom, and check "Allow members to receive and reply to chat messages in the WeChat plug-in"
Turn off the "Only accept messages in Business WeChat" restriction in the Business WeChat client "Me" → "Settings" → "New Message Notification"
PS: For ease of use, the following functions do not cache access_token
. It is enough for personal low-frequency calls. For an implementation with caching, see the sample code in index.php
(depends on Redis implementation).
PHP version:
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 ;
}
Usage examples:
$ ret = send_to_wecom ( "推送测试rn测试换行" , "企业ID③ " , "应用ID① " , "应用secret② " );
print_r ( $ ret );
PYTHON version:
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
Usage examples:
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 version:
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
}
Usage examples:
sendToWecom ( {
text : '推送测试rn测试换行' ,
wecomAgentId : '应用ID①' ,
wecomSecret : '应用secret②' ,
wecomCId : '企业ID③' ,
} )
. then ( ( res ) => {
console . log ( res )
} )
. catch ( ( err ) => {
console . log ( err )
} )
.NET Core version:
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" ;
}
}
Usage examples:
static void Main ( string [ ] args )
{ // 测试
Console . Write ( new WeCom ( ) . SendToWeCom (
"msginfo" ,
"企业Id①"
, "应用secret②" ,
"应用ID③"
) ) ;
}
}
Other versions of functions can be written by referring to the logic above. PRs are welcome.
For advanced usage of sending pictures, cards, files or Markdown messages, see Enterprise WeChat API.