美文网首页
C# 微信公众号开发

C# 微信公众号开发

作者: 小耳朵_c199 | 来源:发表于2019-01-21 16:16 被阅读0次

    1.验证token

            /// <summary>
            /// 初始化
            /// </summary>
            /// <param name="signature"></param>
            /// <param name="timestamp"></param>
            /// <param name="nonce"></param>
            /// <param name="echostr"></param>
            /// <returns></returns>
            public ContentResult Wechat(string signature, string timestamp, string nonce, string echostr)
            {
                WechatBase wechat = WechatBase.GetWechat("wshl");
    
                if (string.IsNullOrEmpty(echostr))
                {
                    using (Stream req = Request.InputStream)
                    {
                        req.Seek(0, System.IO.SeekOrigin.Begin);
                        string xml = new StreamReader(req).ReadToEnd();
                        ///异步调用处理
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            wechat.Subscribe(xml);
                        });
                    }
    
                    return Content("success");
                }
                else
                {
                    if (wechat.CheckSignature(signature, timestamp, nonce, echostr))
                    {
                        return Content(echostr);
                    }
                    return Content("Error!");
                }
            }
    
                    /// <summary>
            /// 校验消息是否来源于微信
            /// </summary>
            /// <param name="signature"></param>
            /// <param name="timestamp"></param>
            /// <param name="nonce"></param>
            /// <param name="echostr"></param>
            /// <returns></returns>
            public bool CheckSign(string signature, string timestamp, string nonce, string echostr)
            {
                List<string> signList = new List<string>();
                signList.Add(timestamp);
                signList.Add(nonce);
                signList.Add(_token);
    
                signList.Sort();
    
                string signStr = string.Join("", signList.ToArray());
                byte[] dataToHash = Encoding.ASCII.GetBytes(signStr);
    
                byte[] hashvalue = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(dataToHash);
    
                StringBuilder sb = new StringBuilder();
    
                foreach (byte b in hashvalue)
                {
                    sb.Append(b.ToString("x2"));
                }
    
                if (signature == sb.ToString())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
    

    2.回复文本消息

    /// <summary>
            /// 给用户发送文本消息
            /// </summary>
            /// <param name="openID"></param>
            /// <param name="message"></param>
            /// <returns></returns>
            public bool SendTextMsg(string openID, string message)
            {
                string url = string.Format("{0}/cgi-bin/message/custom/send?access_token=={1}", _accessPoint, AccessToken);
                string backJson = string.Empty;
                string postJson = new
                {
                    touser = openID,
                    msgtype = "text",
                    text = new 
                    {
                        content = message
                    }
                }.ToJson();
    
                if(_http.Post(ref backJson, url, postJson))
                {
                    JsonBase result = backJson.Deserialize<JsonBase>();
                    if(result.ErrCode == 0)
                    {
                        return true;
                    }
                    return false;
                }
                else
                {
                    return false;
                }
            }
    

    3.回复图片信息

                    /// <summary>
            /// 给用户发送图片消息
            /// </summary>
            /// <param name="openID"></param>
            /// <param name="message"></param>
            /// <returns></returns>
            public bool SendImgMsg(string openID, string message)
            {
                string url = string.Format("{0}/cgi-bin/message/custom/send?access_token=={1}", _accessPoint, AccessToken);
                string backJson = string.Empty;
                string postJson = new
                {
                    touser = openID,
                    template_id = "",
                    data = ""
                }.ToJson();
    
                return true;
            }
    

    4.单个发送模板信息

    /// <summary>
            /// 单个发送模板消息
            /// </summary>
            /// <param name="openID"></param>
            /// <param name="templateID"></param>
            /// <param name="linkUrl"></param>
            /// <param name="data"></param>
            /// <returns></returns>
            public MessageJson SendTemplateMsg(string openID, string templateID, string linkUrl, object data, string color = "black")
            {
                try
                {
                    string url = string.Format("{0}/cgi-bin/message/template/send?access_token={1}", _accessPoint, AccessToken);
                    string backJson = string.Empty;
                    string postJson = new
                    {
                        touser = openID,
                        template_id = templateID,
                        data = data
                    }.ToJson();
    
                    if(_http.Post(ref backJson, url, postJson))
                    {
                        MessageJson msg = backJson.Deserialize<MessageJson>();
                        if(msg == null)
                        {
                            msg = new MessageJson { ErrCode = 99999, ErrMsg = "Wechat:send template message return json:" + backJson };
                        }
                        return msg;
                    }
                    return new MessageJson { ErrCode = 99999, ErrMsg = "Wechat:send template message request failed!" }; ;
                }
                catch(Exception e)
                {
                    Log.WriteLog(e.Message);
                    return new MessageJson { ErrCode = 99999, ErrMsg = e.Message };
                }
            }
    

    6.获取推广信息

    /// <summary>
            /// 获取推广二维码 
            /// </summary>
            /// <param name="action">QR_LIMIT_SCENE/QR_LIMIT_STR_SCENE</param>
            /// <param name="objScene"></param>
            /// <returns></returns>
            public SceneQRResult GetQrUrl(string actionTp, object actionInfo)
            {
                try
                {
                    string url = string.Format("{0}/cgi-bin/qrcode/create?access_token={1}", _accessPoint, AccessToken);
                    string backJson = string.Empty;
                    string postJson = new
                    {
                        action_name = actionTp,
                        action_info = new
                        {
                            scene = actionInfo
                        }
                    }.ToJson();
    
                    if (_http.Post(ref backJson, url, postJson))
                    {
                        SceneQRResult msg = backJson.Deserialize<SceneQRResult>();
    
                        if(msg == null)
                        {
                            return new SceneQRResult { ErrCode = 9999, ErrMsg = "Wechat:deserialize json exception!\r\n" + backJson };
                        }
                        return msg;
                    }
                    return new SceneQRResult { ErrCode = 9999, ErrMsg = "Wechat:QRCode request failed!" };
                }
                catch(Exception e)
                {
                    Log.WriteLog(e.Message);
                    return new SceneQRResult { ErrCode = 9999, ErrMsg = e.Message };
                }
            }
    

    7.显示接收的微信图片
    在head中增加 <meta name="referrer" content="never">

    相关文章

      网友评论

          本文标题:C# 微信公众号开发

          本文链接:https://www.haomeiwen.com/subject/yebcjqtx.html