• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

微信(一)获取openid网页授权C#WeChatHelper

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

用.Net开发微信的时候第一步就是获取微信的网页授权,获取openid。

自己做个总结,以后也好用,这里只提供了获取openid的接口,后续程序有待开发

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Web.Script.Serialization;

namespace WechatHelper
{
    /// <summary>
    /// 在网站下创建WeChat文件夹,将微信页面放在WeChat文件夹下
    /// 调用GetOpenID()方法。
    /// </summary>
    public  class WeChatHelper
    {
        public static string appId = "在微信公共平台中拿";
        public static string secret = "在微信公共平台中拿";
        public static string code = "";


        /// <summary>
        /// 获取openID
        /// </summary>
        /// <param name="type">回调页面的绝对路径</param>
        public static void GetOpenID(string type)
        {
            if ((HttpContext.Current.Request.Cookies["openid"]) == null)
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                Dictionary<string, object> dict = new Dictionary<string, object>();
                string code = GetCode(type);   //获取code
                AccessToken(code); //获取accessToken
                HttpContext.Current.Response.Redirect("/WeChat/" + type + ".aspx");
            }
        }
        /// <summary>
        /// 获取code代码
        /// </summary>
        /// <returns></returns>
        public static string GetCode(string TypeName)
        {
            if (HttpContext.Current.Request.QueryString["Code"] != null)  //判断code是否存在
            {
                if (HttpContext.Current.Request.Cookies["Code"] == null)  //判断是否是第二次进入
                {
                    SetCookie("code", HttpContext.Current.Request.QueryString["Code"], 365);  //写code 保存到cookies
                    code = HttpContext.Current.Request.QueryString["Code"];
                }
                else
                {
                    delCookies("code"); //删除cookies

                    CodeURL(TypeName); //code重新跳转URL
                }
            }
            else
            {
                CodeURL(TypeName); //code跳转URL
            }
            return code;
        }
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string AccessToken(string code)
        {
            Dictionary<string, string> obj = new Dictionary<string, string>();
            var client = new System.Net.WebClient();
            var serializer = new JavaScriptSerializer();
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code);
            client.Encoding = System.Text.Encoding.UTF8;
            string dataaccess = "";
            try
            {
                dataaccess = client.DownloadString(url);
            }
            catch (Exception e)
            {
                //存log方法
            }
            //获取字典
            obj = serializer.Deserialize<Dictionary<string, string>>(dataaccess);
            string accessToken = "";
            if (obj.TryGetValue("access_token", out accessToken))  //判断access_Token是否存在
            {
                SetCookie("openid", obj["openid"], 365);
            }
            else  //access_Token 失效时重新发送。
            {
                //存log方法
            }
            return accessToken;
        }
        /// <summary>
        /// 设置cookies
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="time"></param>
        public static void SetCookie(string name, string value, int time)
        {
            HttpCookie cookies = new HttpCookie(name);
            cookies.Name = name;
            cookies.Value = value;
            cookies.Expires = DateTime.Now.AddDays(time);
            HttpContext.Current.Response.Cookies.Add(cookies);

        }
        /// <summary>
        /// 跳转codeURL
        /// </summary>
        /// <param name="TypeName"></param>
        public static void CodeURL(string TypeName)
        {
            string url = "";
            string locationhref = "http://网站域名/WeChat/"+TypeName+".aspx";
            url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appId, locationhref);
            HttpContext.Current.Response.Redirect(url);
        }
        /// <summary>
        /// 删除cookies
        /// </summary>
        /// <param name="name"></param>
        public static void delCookies(string name)
        {
            foreach (string cookiename in HttpContext.Current.Request.Cookies.AllKeys)
            {
                HttpCookie cookies = HttpContext.Current.Request.Cookies[name];
                if (cookies != null)
                {
                    cookies.Expires = DateTime.Today.AddDays(-1);
                    HttpContext.Current.Response.Cookies.Add(cookies);
                    HttpContext.Current.Request.Cookies.Remove(name);
                }
            }
        }
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Newtonsoft.Json(C#处理json)发布时间:2022-07-14
下一篇:
c#根据自定义Attribute排序发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap