天天看點

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),點選上面的微信登入圖示就可以實作微信掃碼登入,如果有不明白的可以評論