Enterprise WeChat을 통해 WeChat에 메시지를 푸시하는 솔루션입니다. 포함하다:
이점:
추신: 메시징 인터페이스는 인증 없이 사용할 수 있습니다. 개인은 WeChat을 사용하여 등록할 수 있습니다.
컴퓨터를 사용하여 공식 기업 WeChat 웹사이트를 열고 회사를 등록하세요.
성공적으로 등록한 후 "기업 관리"를 클릭하여 관리 인터페이스로 들어가 "애플리케이션 관리" → "자체 구축" → "애플리케이션 생성"을 선택합니다.
애플리케이션 이름에 "서버 소스"를 입력하고 여기에서 애플리케이션 로고를 다운로드한 후 가시 범위에 대한 회사명을 선택합니다.
생성이 완료되면 애플리케이션 상세페이지에 들어가시면 애플리케이션 ID( agentid
)①와 애플리케이션 시크릿( secret
)②을 받으실 수 있습니다.
참고: secret
휴대폰에 푸시되면企业微信客户端
에서만 볼 수 있습니다.
2022년 6월 20일 이후에 생성된 애플리케이션은 신뢰할 수 있는 IP를 추가로 구성해야 합니다.
"애플리케이션 세부정보 페이지" 하단의 개발자 인터페이스 카테고리에서 "Enterprise Trusted IP"를 찾아 "구성"을 클릭하고 서버 IP를 입력하세요.
Cloud Function과 같은 공용 IP 클라우드 서비스를 사용하는 경우 독립 IP를 얻기 위해 (Cloud Function 또는 기타 서비스의) 설정 인터페이스에서 "고정 공용 IP"를 활성화해야 할 수도 있습니다. 그렇지 않으면 "타사 서비스 IP" 오류가 보고될 수 있습니다.
"마이비즈니스" 페이지에 접속하여 하단으로 스크롤하시면 사업자번호가 보입니다 ③, 복사하여 상단까지 작성해주세요.
UID를 푸시하려면 @all
직접 입력하고 회사의 모든 직원에게 푸시하세요.
"마이 비즈니스" → "WeChat 플러그인"에 들어가서 아래로 스크롤하여 QR 코드를 스캔하고 따라가면 푸시 메시지를 받을 수 있습니다.
추신:接口请求正常,企业微信接受消息正常,个人微信无法收到消息
.
'마이 비즈니스' → 'WeChat 플러그인'으로 이동하여 하단으로 스크롤한 후 '회원이 WeChat 플러그인에서 채팅 메시지를 받고 답장할 수 있도록 허용'을 선택합니다.
비즈니스 WeChat 클라이언트 "나" → "설정" → "새 메시지 알림"에서 "비즈니스 WeChat에서만 메시지 수락" 제한을 해제하세요.
추신: 사용 편의성을 위해 다음 함수는 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 ( "推送测试rn测试换行" , "企业ID③ " , "应用ID① " , "应用secret② " );
print_r ( $ ret );
파이썬 버전:
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 );
타입스크립트 버전:
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 : '推送测试rn测试换行' ,
wecomAgentId : '应用ID①' ,
wecomSecret : '应用secret②' ,
wecomCId : '企业ID③' ,
} )
. then ( ( res ) => {
console . log ( res )
} )
. catch ( ( err ) => {
console . log ( err )
} )
.NET 코어 버전:
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③"
) ) ;
}
}
위의 논리를 참조하여 다른 버전의 함수를 작성할 수 있습니다.
사진, 카드, 파일 또는 마크다운 메시지 전송에 대한 고급 사용법은 Enterprise WeChat API를 참조하세요.