zoukankan      html  css  js  c++  java
  • asp.net微信开发第一篇----开发者接入

    以上是微信官方后台需要设置的,

    以下是我们自己的程序页面对接配置的一些设置:

    字段说明:

    平台名称:看图片,关注公众号时显示的欢迎关注(平台名称)

    APPID:这个必须和微信官网的一致

    Appsecret:这个必须和微信官网的一致

    Token:这个必须和微信官网的一致

    授权域名:这个必须是微信官网设置的授权回调页面地址是一样的,

    功能说明:这个就是关注公众号时显示的图文消息下的那几段话,

    官方网址:这个就是点击关注公众号时显示的图文消息的跳转地址

    关注时的图片:这个就是点击关注公众号时显示的图文消息的图片

    处理方法:把字段信息保存到本地数据库,这里呢,我设置了两个,如果你关注了微信测试号本地测试时使用另外一个,真正的项目就切换到另外一个

    设置好以后,还没有启用这个配置,只需点击一下设置默认(只是将状态更改为1而已)即可,随后,在页面调用的时候,调用微信服务类

    代码如下:

      /// <summary>
            /// 获取微信公众号的AppId
            /// </summary>
            public static string GetAppId()
            {
                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                if (wcfInfo != null)
                {
                    return wcfInfo.wechat_AppId.ToString();
                }
                return null; ;
            }
    
            /// <summary>
            /// 获取微信公众号的AppSecret
            /// </summary>
            public static string GetAppSecret()
            {
                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                if (wcfInfo != null)
                {
                    return wcfInfo.wechat_AppSecret.ToString();
                }
                return null; ;
            }
    
            /// <summary>
            /// 获取本地设置的Token
            /// </summary>
            public static string GetToken()
            {
                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                if (wcfInfo != null)
                {
                    return wcfInfo.wechat_Token.ToString();
                }
                return null; ;
            }
    
            /// <summary>
            /// 获取网页授权域名
            /// </summary>
            public static string GetpostUrl()
            {
                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                if (wcfInfo != null)
                {
                    return wcfInfo.wechat_PostUrl.ToString();
                }
                return null; ;
            }
    
            /// <summary>
            /// 获取通行证
            /// </summary>
            /// <returns></returns>
            public  string GetAccessToken()
            {
                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                string appid = "";
                string secret = "";
                if (wcfInfo != null)
                {
                    //初始化微信配置信息
                    appid = wcfInfo.wechat_AppId.ToString();
                    secret = wcfInfo.wechat_AppSecret.ToString();
                }
    
                string url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url_token);
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                return content;
            }

    在项目的根目录或者特定的文件夹内,创建一个ashx文件(一般处理程序文件),如图

     public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
              
                string postString = string.Empty;
                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))
                    {
                        ResponseXML(postString);//返回给微信用户信息
                    }
    
                    ///加载自定义菜单
                    StringBuilder sb = new StringBuilder();
                    sb.Append("{");
                    sb.Append(""button":[ ");
                    sb.Append("{ ");
                    sb.Append(""name":"好好学习",");
                    sb.Append(""sub_button":[");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"微学堂", ");
                    sb.Append(""key":"weixuetang"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"大咖说", ");
                    sb.Append(""key":"dakashuo"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"好书推荐", ");
                    sb.Append(""key":"haoshutuijian"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"讲师风采", ");
                    sb.Append(""key":"jiangshifengcai"");
                    sb.Append("}]");
                    sb.Append("},");
                    sb.Append("{");
                    sb.Append(""name":"天天向上", ");
                    sb.Append(""sub_button":[");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"看见", ");
                    sb.Append(""key":"kanjian"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"撩我", ");
                    sb.Append(""key":"liaowo"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"view",");
                    sb.Append(""name":"文化UP", ");
                    sb.Append(""url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeiXinServer.GetAppId().ToString()+"&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl().ToString()+"/wenhuaup/wenhua_home.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"萝卜快来", ");
                    sb.Append(""key":"luobokuailai"");
                    sb.Append("}]");
                    sb.Append("},");
                    sb.Append("{");
                    sb.Append(""name":"员工自助",");
                    sb.Append(""sub_button":[");
                    sb.Append("{ ");
                    sb.Append(""type":"click",");
                    sb.Append(""name":"我的薪资", ");
                    sb.Append(""key":"mysalary"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"view",");
                    sb.Append(""name":"个人中心", ");
                    sb.Append(""url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinServer.GetAppId().ToString() + "&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl()+"/UserLogin.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect"");
                    sb.Append("},");
                    sb.Append("{ ");
                    sb.Append(""type":"view",");
                    sb.Append(""name":"在线提问", ");
                    sb.Append(""url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinServer.GetAppId().ToString() + "&redirect_uri=" + HttpUtility.UrlEncode(""+WeiXinServer.GetpostUrl()+"/UserCenter/question/MyQuestion.aspx") + "&response_type=code&scope=snsapi_base&state=" + new Random().Next(1000, 200000).ToString() + "#wechat_redirect"");
                    sb.Append("}]");
                    sb.Append("}]");
                    sb.Append("}");

                    //自定义菜单token的获取 是用 下面的两个参数 获取的 不能直接用 公众平台的token
                    string to = GetAccessToken();
                    //本人不喜欢 后台 json的操作 直接截取就可以了 得到的就是 token 或者 自己 获取 json的token
                    to = to.Substring(17, to.Length - 37);
                    //加载菜单
                    string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + to, sb.ToString());
    } else { Auth(); //微信接入的测试 } }  /// <summary>
            /// 获取通行证
            /// </summary>
            /// <returns></returns>
            public string GetAccessToken()
            {
                string url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinServer.GetAppId().ToString() + "&secret=" + WeiXinServer.GetAppSecret().ToString();
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url_token);
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                return content;
            }
    /// <summary> /// 加载菜单项 /// </summary> /// <param name="p"></param> /// <param name="postData"></param> /// <returns></returns> private string GetPage(string p, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(p) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return string.Empty; } } /// <summary> /// 获取参数进行认证 /// </summary> private void Auth() {   string token = WeiXinServer.GetToken().ToString();//你申请的时候填写的Token,必须和微信上的保持一致 string echoString = HttpContext.Current.Request.QueryString["echoStr"]; string signature = HttpContext.Current.Request.QueryString["signature"]; string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; if (CheckSignature(token, signature, timestamp, nonce)) { if (!string.IsNullOrEmpty(echoString)) { HttpContext.Current.Response.Write(echoString); HttpContext.Current.Response.End(); } } } /// <summary> /// 对微信传入参数进行封装到数组,拼接字符串,进行加密操作 /// </summary> /// <param name="token"></param> /// <param name="signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <returns></returns> private bool CheckSignature(string token, string signature, string timestamp, string nonce) { string[] ArrTmp = { token, timestamp, nonce };//将参数放进数组 Array.Sort(ArrTmp);//对数组进行排序 string tmpStr = string.Join("", ArrTmp);//将数组进行拼接 ///对拼接后的字符串进行加密操作 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); //转换成小写形式 tmpStr = tmpStr.ToLower(); //比对成功返回 if (tmpStr == signature) { return true; } else { return false; } }

     /// <summary>
            /// 点击关注平台后,主动发送给用户关注后的消息推送
            /// </summary>
            /// <param name="requestXML"></param>
            private void SendWelComeMsg(RequestXML requestXML)
            {
                String responseContent = String.Empty;

                string newdate = DateTime.Now.Subtract(new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds.ToString();

                string PUrlfileName = "";
                string companyName = "";
                string description = "";
                string companywebsite = "";

                //获取使用中的微信配置信息
                WeChatConfigService wcf = new WeChatConfigService();
                WeChatConfigInfo wcfInfo = wcf.GetWeChatConfigInfoByInUse();
                if (wcfInfo != null)
                {
                    //初始化微信配置信息
                    PUrlfileName = WeiXinServer.GetpostUrl().ToString() + "/img/focus/" + wcfInfo.focus_Image.ToString();
                    companyName = wcfInfo.wechat_Name.ToString();
                    description = wcfInfo.description.ToString();
                    companywebsite = wcfInfo.company_website.ToString();
                }

                responseContent = string.Format(Message_News_Main, requestXML.FromUserName, requestXML.ToUserName, newdate, "1",
                    string.Format(Message_News_Item, "欢迎关注" + companyName, description, PUrlfileName, companywebsite));


                HttpContext.Current.Response.ContentType = "text/xml";
                HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
                HttpContext.Current.Response.Write(responseContent);
            }
  • 相关阅读:
    ABB机器人 带参数例行程序
    面试题10- I:斐波那契数列(C++)
    面试题39:数组中出现次数超过一半的数字(C++)
    面试题50:第一个只出现一次的字符(C++)
    第八部分 表的基本操作
    第七部分 表中数据的基本操作
    面试题18:删除链表的节点(C++)
    面试题35:复杂链表的复制(C++)
    面试题54:二叉搜索树的第k大节点(C++)
    面试题62:圆圈中最后剩下的数字(C++)
  • 原文地址:https://www.cnblogs.com/shaojiang/p/4901431.html
Copyright © 2011-2022 走看看