Ejemplo n.º 1
0
        public IActionResult HttpGetTest()
        {
            //Task<string> taskGetToken = _weChatAPI.GetAccessTokenAsync();
            //taskGetToken.Wait();
            //_logger.Debug(taskGetToken.Result);



            //Task<string> taskGetAccessToken = _weChatAPI.GetAccessTokenAsync();

            //taskGetAccessToken.Wait();

            //string _accessToken = JSONFormatting<AccessToken>.JsonToClass(taskGetAccessToken.Result).access_token;

            string _accessToken = "28_K2O8C0JWZGM2XguSgS8x-frs3nQyiQywTn85uuqubhMhnBGNCmVD96p0YoqtQ7GF_v9_sT9-20ORuN1FDlI4c3ecSZi1Whx3RQbQbocvaTWHq4u_VZEmOopvcBWBh6GjTHuNvmJj2WY91VdZGVBjABANCI";

            _logger.Debug(_accessToken);

            Task <string> getUserInfo = _weChatAPI.GetSubscriberInfo(_accessToken, "oQn7Pv0i5Y65EL-mdgT11KbhLK6g");

            getUserInfo.Wait();

            var userInfo = Formatting <WeChatUserInfo> .JsonToClass(getUserInfo.Result);

            _logger.Debug(userInfo.nickname);


            return(Ok());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> PublicAccountCallbackPost([FromQuery] string signature, [FromQuery] string timestamp, [FromQuery] string nonce, [FromQuery] string echostr)
        {
            try
            {
                CheckSignature checkSignature = new CheckSignature(_weChatSettings.Value.token);

                // Check if signature matches
                if (!checkSignature.IsValidSignature(timestamp, nonce, signature))
                {
                    // Unauthorized call
                    _logger.Warn("Unauthroized call!",
                                 Request.HttpContext.Connection.RemoteIpAddress?.ToString(),
                                 $"signature:{signature}, nonce:{nonce}, echostr:{echostr}");
                    return(Unauthorized());
                }


                // Authorized call
                using (var reader = new StreamReader(Request.Body))
                {
                    // Read message
                    var body = await reader.ReadToEndAsync();

                    // log original response
                    _logger.Info(body);

                    var messageXml = Formatting <MessageXml> .XmlToClass(body);


                    // Check access_token
                    if (!_cacheControl.IsCacheExist("access_token"))
                    {
                        // access token is not cached or expired, using wechat API to get a new one, then save it in cache
                        Task <string> taskGetAccessToken = _weChatAPI.GetAccessTokenAsync();
                        taskGetAccessToken.Wait();
                        _accessToken = Formatting <AccessToken> .JsonToClass(taskGetAccessToken.Result).access_token;

                        _cacheControl.SetCache("access_token", _accessToken, 60 * 60);
                    }
                    else
                    {
                        // access token is cached, retrieve it
                        _accessToken = _cacheControl.GetValueBykey("access_token").ToString();
                    }



                    // Different handlers for each type of message
                    if (messageXml.MsgType == "text")
                    {
                        TextMessageXml textMessageXml = Formatting <TextMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({textMessageXml.FromUserName}) post text message {textMessageXml.Content}");



                        // fetch user information
                        // IF username is already existed in somewhere like a local database, then we do not need to get info every time.
                        // But it is a callback so performance wise it does not really matter so much.
                        Task <string> taskGetUserInfo = _weChatAPI.GetSubscriberInfo(_accessToken, textMessageXml.FromUserName);
                        taskGetUserInfo.Wait();
                        WeChatUserInfo weChatUserInfo = Formatting <WeChatUserInfo> .JsonToClass(taskGetUserInfo.Result);


                        // TODO: auto reply
                    }
                    else if (messageXml.MsgType == "voice")
                    {
                        VoiceMessageXml voiceMessageXml = Formatting <VoiceMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({voiceMessageXml.FromUserName}) post voice message {voiceMessageXml.Recognition}. (Media Id:{voiceMessageXml.MediaId}, Format: {voiceMessageXml.Format})");
                    }
                    else if (messageXml.MsgType == "image")
                    {
                        ImageMessageXml imageMessageXml = Formatting <ImageMessageXml> .XmlToClass(body);

                        _logger.Info($"User ({imageMessageXml.FromUserName}) post image {imageMessageXml.PicUrl}. (Media Id:{imageMessageXml.MediaId})");
                    }
                }
                return(Ok(echostr));
            }
            catch (Exception e)
            {
                _logger.Error("************");
                _logger.Error(e.ToString());
                _logger.Error("************");
                return(Ok(echostr));
            }
        }