C#实现微信扫码登录

第一步:获取AppID AppSecret(去微信开放平台申请网址https://open.weixin.qq.com/)
第二步:生成扫描二维码,获取code
https://open.weixin.qq.com/connect/qrconnect?appid=yourAppId&redirect_uri=http%3A%2F%2Fwww.shisezhe.com%2Fcallback%2FweixinLogin.html&response_type=code&scope=snsapi_login&state=" + random + “#wechat_redirect”
(注:
appid是在微信开入平台申请通过后获得的appID,
redirect_uri(重定向地址,需要进行UrlEncode,实现登录接口后自己网站的页面处理,比如跳转到会员后台页面)
response_type:code(写死的,不用管它)
state:(用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验,我是用的生成的随机数,放在session里,等一下验证)

然后就是调用接口代码
用一个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class callback_WeixinLogin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["loginState"] != null && Request.QueryString["state"] != null && Request.QueryString["code"] != null)
        {
            string state = Request.QueryString["state"].ToString();
            if (!Session["loginState"].ToString().Equals(state))
            {
                Response.Redirect("../Reminder-reviewError.html");
                Response.End();
            }
            else
            {
                string code = Request.QueryString["code"].ToString();


                QQ_callback qq_callback = new QQ_callback();
                //通过code获取微信用户的资料,下面贴代码 
                Weixin_info weixin_info = qq_callback.getWeixinUserInfoJSON(code);


                string openId = weixin_info.unionid;
                Handler handler = new Handler();
                string userId = handler.GetCallback(openId);
                string userName = weixin_info.nickname;
                string sex = weixin_info.sex;
                    if ("1".Equals(sex))
                    {
                        sex = "男";
                    }
                    else if ("0".Equals(sex))
                    {
                        sex = "女";
                    }
                    else
                    {
                        sex = "保密";
                    }
                    string userSex = sex;
                    

                    string pwd = "123456;//初始密码
                    pwd = Encrypt.MD5.MD5Encrypt(pwd);

                    
                    string province = weixin_info.province;
                    //string city = weixin_info.city;
                   
                    string prId = "";
                    string dqqy = "";

                    string lgoinMode = "WeiXin";
                    //获取ip
                    string memberIP = handler.GetHostAddress();
                    //登录信息存到数据库,初始密码123456
                    handler.AddQQTempMember(openId, pwd, memberIP, userName, userSex, prId, dqqy, lgoinMode);

	                 //登录成功,跳转到会员中心首页
                     Response.Redirect("../member/index.html");
              

            }
        }
        else
        {
            //如果没有获得几个参数就重定向到自己定义的错误提示页面
            Response.Redirect("../Reminder-reviewError.html");
            //Response.End();
        }

     
    }
}

通过微信code获到用户微信的资料信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Text;

/// <summary>
///QQ_callback 的摘要说明
/// </summary>
public class QQ_callback
{
	public QQ_callback()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
 /// <summary>
    /// 获得Weixn回调信息字符串json
    /// </summary>
    /// <param name="code">Authorization Code</param>
    /// <returns></returns>
    public Weixin_info getWeixinUserInfoJSON(string code)
    {

        string appid = "你在微信开放平台申请通过后的获得的appid";
        string secret = "你在微信开放平台申请通过后的获得的secret";


        string apiurl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid,secret, code);
                                 
        System.GC.Collect();
        System.Net.ServicePointManager.DefaultConnectionLimit = 200;
        WebRequest request = WebRequest.Create(apiurl);

        WebResponse response = request.GetResponse();

        Stream stream = response.GetResponseStream();
        Encoding encode = Encoding.UTF8;
        StreamReader reader = new StreamReader(stream, encode);
        string jsonText = reader.ReadToEnd();

        JObject jo1 = (JObject)JsonConvert.DeserializeObject(jsonText);
        string access_token = jo1["access_token"].ToString();
        string refresh_token = jo1["refresh_token"].ToString();
        string openid = jo1["openid"].ToString();


        string url_me = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}",appid, refresh_token);
        request = WebRequest.Create(url_me);
        response = request.GetResponse();
        stream = response.GetResponseStream();
        reader = new StreamReader(stream, encode);
        string openIdStr = reader.ReadToEnd();


        JObject jo = (JObject)JsonConvert.DeserializeObject(openIdStr);
        
        //string access_token = jo["access_token"].ToString();
        string openId = jo["openid"].ToString();

        根据OpenID获取用户信息 可以显示更多 用的就几个 需要的可以自己在下面加
        string getinfo = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}", access_token, openId);
        request = WebRequest.Create(getinfo);
        response = request.GetResponse();
        stream = response.GetResponseStream();
        reader = new StreamReader(stream, encode);
        string userStr = reader.ReadToEnd();
        //this.Label1.Text = userStr;
        //this.Label2.Text = openIdStr;
        JObject info = (JObject)JsonConvert.DeserializeObject(userStr);
        
        Weixin_info weixin_info = new Weixin_info();//自己定义的dto
        weixin_info.openId = openId;
        weixin_info.nickname = info["nickname"].ToString();
        weixin_info.sex = info["sex"].ToString();
        weixin_info.province = info["province"].ToString();
        weixin_info.city = info["city"].ToString();
        weixin_info.headimgurl = info["headimgurl"].ToString();//大小为30×30像素的QQ空间头像URL。
        weixin_info.unionid = info["unionid"].ToString();//用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
        reader.Close();
        stream.Flush();
        stream.Close();
        response.Close();
        return weixin_info;
    }
}

自己定义的Weixin_infodto

public class Weixin_info
{

    public string openId { get; set; }//普通用户的标识,对当前开发者帐号唯一
    public string nickname { get; set; }//普通用户昵称
    public string sex { get; set; }//普通用户性别,1为男性,2为女性
    public string province { get; set; }//普通用户个人资料填写的省份

    public string city { get; set; }//普通用户个人资料填写的城市

    public string headimgurl { get; set; }//用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
    public string unionid { get; set; }//用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
}

以上代码就可以实现微信扫码登录
演示网址(https://www.shisezhe.com/login.html),点击上面的微信登录图标就可以实现微信扫码登录,如果有不明白的可以评论

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值