목차
2. WeChat 콜백 메시지 확인
3. 기업 계정의 메시지 처리
위챗 애플릿 위챗 개발 C#은 WeChat 포털을 개발하고 WeChat 엔터프라이즈 계정을 사용하여 메시지와 이벤트를 수신, 처리 및 해독합니다.

C#은 WeChat 포털을 개발하고 WeChat 엔터프라이즈 계정을 사용하여 메시지와 이벤트를 수신, 처리 및 해독합니다.

Mar 02, 2017 am 09:29 AM

1. 기업 계정의 콜백 모드 설정

공개 계정과 유사하게 WeChat 기업 계정에 2차 개발이 필요한 경우 해당 콜백 매개변수를 백그라운드에서 설정해야 합니다. 다음 인터페이스.

C#은 WeChat 포털을 개발하고 WeChat 엔터프라이즈 계정을 사용하여 메시지와 이벤트를 수신, 처리 및 해독합니다.

이를 설정하고 확인을 통과하면 자체 WeChat 애플리케이션 서버에서 메시지를 보내고 받을 수 있습니다.

콜백 메시지 입력 시 POST 데이터와 일반 GET 데이터를 별도로 처리해야 합니다. GET 데이터는 WeChat 자체 확인 처리이고 POST 데이터는 WeChat 메시지의 대화형 작업입니다.

    /// <summary>
    /// 企业号回调信息接口。统一接收并处理信息的入口。    /// </summary>
    public class corpapi : IHttpHandler
    {        /// <summary>
        /// 处理企业号的信息        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
로그인 후 복사

위에서 우리는 메시지를 처리하는 일반 애플리케이션 핸들러를 정의했습니다.

그런 다음 다양한 메시지 유형(POST, GET 방식)을 분리하여 그에 따라 처리합니다.

                    if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
                    {                        using (Stream stream = HttpContext.Current.Request.InputStream)
                        {
                            Byte[] postBytes = new Byte[stream.Length];
                            stream.Read(postBytes, 0, (Int32)stream.Length);
                            postString = Encoding.UTF8.GetString(postBytes);
                        }                        if (!string.IsNullOrEmpty(postString))
                        {
                            Execute(postString, accountInfo);
                        }
                    }                    else
                    {
                        Auth(accountInfo);
                    }
로그인 후 복사

2. WeChat 콜백 메시지 확인

다음은 WeChat의 콜백 모드 및 확인 URL에 대한 지침입니다.

URL 유효성 확인

위 정보를 제출하면 기업 계정은 입력된 URL로 GET 요청을 보냅니다. GET 요청에는 4개의 매개변수가 포함됩니다. 기업은 을 얻을 때 urldecode 처리를 수행해야 합니다. 그렇지 않으면 확인이 실패합니다.

参数描述是否必带
msg_signature微信加密签名,msg_signature结合了企业填写的token、请求中的timestamp、nonce参数、加密的消息体
timestamp时间戳
nonce随机数
echostr加密的随机字符串,以msg_encrypt格式提供。需要解密并返回echostr明文,解密后有random、msg_len、msg、$CorpID四个字段,其中msg即为echostr明文首次校验时必带

기업은 msg_signature 매개변수를 통해 요청을 확인합니다. GET 요청이 기업 계정에서 온 것으로 확인되면 기업 애플리케이션은 echostr 매개변수를 해독하고 echostr 일반 텍스트를 다음과 같이 반환합니다. (따옴표 없음)이면 액세스 인증이 적용되고 콜백 모드를 켤 수 있습니다.

이후 기업에 콜백이 이루어질 때 위의 매개변수(echostr 제외)가 요청 URL에 포함되며, 확인 방법은 첫 번째 확인 URL과 동일합니다.

위 지침에 따라 이러한 매개변수를 얻은 다음 WeChat에서 제공하는 메시지 처리 기능을 호출하여 암호화 및 암호 해독 처리를 수행해야 합니다.

URL을 확인하는 Auth(accountInfo); 작업에서 전달된 매개변수 정보를 얻은 후 이를 기본 클래스에 전달하여 처리하는 핵심 내용은 다음과 같음을 알 수 있습니다. 메시지의 서명 내용.

                        #region 具体处理逻辑                        string echoString = HttpContext.Current.Request.QueryString["echoStr"];                        string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
                        string timestamp = HttpContext.Current.Request.QueryString["timestamp"];                        string nonce = HttpContext.Current.Request.QueryString["nonce"];                        string decryptEchoString = "";                        if (new CorpBasicApi().CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
                        {                            if (!string.IsNullOrEmpty(decryptEchoString))
                            {
                                HttpContext.Current.Response.Write(decryptEchoString);
                                HttpContext.Current.Response.End();
                            }
                        } 
                        #endregion
로그인 후 복사

인증코드 부서는 아래와 같습니다.

        /// <summary>
        /// 验证企业号签名        /// </summary>
        /// <param name="token">企业号配置的Token</param>
        /// <param name="signature">签名内容</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">nonce参数</param>
        /// <param name="corpId">企业号ID标识</param>
        /// <param name="encodingAESKey">加密键</param>
        /// <param name="echostr">内容字符串</param>
        /// <param name="retEchostr">返回的字符串</param>
        /// <returns></returns>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
        {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);            int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);            if (result != 0)
            {
                LogTextHelper.Error("ERR: VerifyURL fail, ret: " + result);                return false;
            }            return true;
        }
로그인 후 복사

3. 기업 계정의 메시지 처리

위에서 소개한 것처럼 URL에 대한 WeChat 기업 계정의 확인 과정에는 또 다른 메시지가 있습니다. 처리 프로세스는 WeChat 서버가 처리를 위해 메시지를 자체 애플리케이션 서버로 보내는 프로세스입니다. 당사 애플리케이션 서버는 메시지를 수신한 후 적시에 정기적인 응답 처리를 수행해야 합니다.

은 아래의 코드 로직입니다.

                    if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
                    {                        using (Stream stream = HttpContext.Current.Request.InputStream)
                        {
                            Byte[] postBytes = new Byte[stream.Length];
                            stream.Read(postBytes, 0, (Int32)stream.Length);
                            postString = Encoding.UTF8.GetString(postBytes);
                        }                        if (!string.IsNullOrEmpty(postString))
                        {
                            Execute(postString, accountInfo);
                        }
                    }
로그인 후 복사

마찬가지로 WeChat 서버에 대한 메시지에 응답할 때 해당 매개변수도 가져온 다음 메시지 응답을 구성해야 합니다.

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];            string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];            string nonce = HttpContext.Current.Request.QueryString["nonce"];
로그인 후 복사

그리고 일부 다른 매개변수 정보는 기업 계정의 구성 매개변수에서 가져옵니다.

            //获取配置参数并对加解密函数初始化
            string CorpToken = accountInfo.Token;            string AESKey = accountInfo.EncodingAESKey;            string CorpId = accountInfo.CorpID;
로그인 후 복사

그런 다음 WeChat에서 제공하는 메시지 암호화 및 복호화 클래스를 사용하여 메시지를 성공적으로 암호화하고 복호화합니다. 구체적인 연산 코드는 다음과 같습니다.

            //根据参数信息,初始化微信对应的消息加密解密类
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(CorpToken, AESKey, CorpId);            //对收到的密文进行解析处理
            string sMsg = "";  // 解析之后的明文
            int flag = wxcpt.DecryptMsg(signature, timestamp, nonce, postStr, ref sMsg);            if (flag == 0)
            {                //LogTextHelper.Info("记录解密后的数据:");                //LogTextHelper.Info(sMsg);//记录解密后的数据
                CorpApiDispatch dispatch = new CorpApiDispatch();                string responseContent = dispatch.Execute(sMsg);                //加密后并发送                //LogTextHelper.Info(responseContent);
                string encryptResponse = "";
                timestamp = DateTime.Now.DateTimeToInt().ToString();
                wxcpt.EncryptMsg(responseContent, timestamp, nonce, ref encryptResponse, ref signature);

                HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
                HttpContext.Current.Response.Write(encryptResponse);
            }            else
            {
                LogTextHelper.Info("解密消息失败!");
            }
로그인 후 복사

마지막으로, 통합 처리를 위해 복호화된 메시지를 해당 캡슐화 클래스에 넘겨주기만 하면 됩니다.

                CorpApiDispatch dispatch = new CorpApiDispatch();                string responseContent = dispatch.Execute(sMsg);
로그인 후 복사

이런 방식으로 Enterprise API를 캡슐화할 때 메시지에 응답하는 방법의 논리에만 집중하면 됩니다. 나머지도 신경써야 해요.

C#은 WeChat 포털을 개발하고 WeChat 엔터프라이즈 계정을 사용하여 메시지와 이벤트를 수신, 처리 및 해독합니다.


WeChat 포털의 추가 C# 개발 및 WeChat 기업 계정 수신, 메시지 처리 및 암호 해독 애플리케이션 이벤트 관련 기사는 PHP 중국어 홈페이지를 주목해주세요!


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)