asp.net version of the micro-letter Web login authorization, access to user information examples

Source: Internet
Author: User
Tags httpcontext openid


asp.net version of micro-letter Web login authorization must be a micro-public number and type "service number"

First you need to look at the micro-mail API documentation.

Micro-trust Web page authorization, access to the user's micro-credit official API document address:
Http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html


Micro-Credit Certification process:

1 First step: User consent authorization, get code
2 Second step: Through code in exchange for Web page authorization Access_token
3 Step Three: Refresh Access_token (if required)
4 Fourth Step: Pull user information (need scope for snsapi_userinfo)
5 attached: Verify the validity of the authorization voucher (Access_token)

Ideas:

After research, my side of the idea is: let all pages inherit the same page, in this page to do the micro-letter login Authorization processing,
Because the first step must be through the micro-letter login authorization, not the Web page back-end request, so first of all through the user agreed to request the Assembly through the page of the micro-letter request link. Request the link,
After obtaining the code, the backend simulates the request. Get user information.

Micro-letter three-time handshake Method (code)

public class Weixinoauth
{
<summary>
Get the micro-credit code
</summary>
<param name= "AppId" ></param>
<param name= "Appsecret" ></param>
<param name= "RedirectURL" ></param>
public string Getweixincode (string appid,string appsecret,string RedirectURL)
{
Random r = new Random ();
Micro-Letter Login Authorization
String url = "Https://open.weixin.qq.com/connect/qrconnect?appid=" + AppID + "&redirect_uri=" + RedirectURL + " &response_type=code&scope=snsapi_login&state=state#wechat_redirect ";
Micro-Letter OpenID Authorization
String url = "Https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppID + "&redirect_uri=" + RedirectURL + "&response_type=code&scope=snsapi_login&state=state#wechat_redirect";
Micro-Credit User Information authorization
String url = "Https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppID + "&redirect_uri=" + RedirectURL + "&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect";

return URL;
}
<summary>
Get Access_token by code
</summary>
<param name= "AppId" ></param>
<param name= "Appsecret" ></param>
<param name= "Code" ></param>
<returns></returns>
Public Model.weixinaccesstokenresult Getweixinaccesstoken (string appid,string appsecret,string code)
{
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +appid+ "&secret=" +appsecret+
"&code=" + code + "&grant_type=authorization_code";
String jsonstr = tools.gethttprequest (URL);

Model.weixinaccesstokenresult result = new Model.weixinaccesstokenresult ();
if (Jsonstr.contains ("Errcode"))
{
Model.weixinerrormsg Errorresult = new Model.weixinerrormsg ();
Errorresult=jsonhelper.parsefromjson<model.weixinerrormsg> (JSONSTR);
Result. Errorresult = Errorresult;
Result. result = false;
}
Else
{
Model.weixinaccesstokenmodel model = new Model.weixinaccesstokenmodel ();
Model = jsonhelper.parsefromjson<model.weixinaccesstokenmodel> (JSONSTR);
Result. Successresult = model;
Result. result = true;
}
return result;
}
<summary>
Pull User Information
</summary>
<param name= "Accesstoken" ></param>
<param name= "OpenId" ></param>
<returns></returns>
Public Model.weixinuserinforesult getweixinuserinfo (string accesstoken,string openId)
{
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +accesstoken+ "&openid=" +openid+ &lang= ZH_CN ";

String jsonstr = tools.gethttprequest (URL);
Model.weixinuserinforesult result = new Model.weixinuserinforesult ();
if (Jsonstr.contains ("Errcode"))
{
Model.weixinerrormsg Errorresult = new Model.weixinerrormsg ();
Errorresult = jsonhelper.parsefromjson<model.weixinerrormsg> (JSONSTR);
Result. ErrorMsg = Errorresult;
Result. result = false;
}
Else
{
Model.weixinuserinfo userInfo = new Model.weixinuserinfo ();
UserInfo = jsonhelper.parsefromjson<model.weixinuserinfo> (JSONSTR);
Result. UserInfo = UserInfo;
Result. result = true;
}
return result;
}
}
Required corresponding entity classes

Weixinaccesstokenresult class:

Micro-Credit development notes-micro-letter Web login authorization, access to user information
Micro-Credit development notes-micro-letter Web login authorization, access to user information
public class Weixinaccesstokenresult
{
Public Weixinaccesstokenmodel Successresult {get; set;}
public bool Result {get; set;}

Public weixinerrormsg Errorresult {get; set;}

}
View Code
Weixinaccesstokenmodel class:
Micro-Credit development notes-micro-letter Web login authorization, access to user information
Micro-Credit development notes-micro-letter Web login authorization, access to user information
<summary>
Get Access_token request successful entity by code
</summary>
public class Weixinaccesstokenmodel
{
<summary>
Interface Call Credentials
</summary>
public string Access_token {get; set;}
<summary>
Access_token interface Call voucher timeout time, in seconds
</summary>
public int expires_in {get; set;}
<summary>
User Refresh Access_token
</summary>
public string Refresh_token {get; set;}
<summary>
Authorized User Unique identification
</summary>
public string OpenID {get; set;}
<summary>
User-authorized scope, separated by commas (,)
</summary>
public string Scope {get; set;}
}
View Code
Weixinerrormsg class:
Micro-Credit development notes-micro-letter Web login authorization, access to user information
Micro-Credit development notes-micro-letter Web login authorization, access to user information
<summary>
The situation of the micro-credit error access
</summary>
public class Weixinerrormsg
{
<summary>
Error number
</summary>
public int Errcode {get; set;}
<summary>
Error prompt message
</summary>
public string ErrMsg {get; set;}
}
View Code
Weixinuserinforesult class:

Micro-Credit development notes-micro-letter Web login authorization, access to user information
Micro-Credit development notes-micro-letter Web login authorization, access to user information
<summary>
Access to micro-credit user information
</summary>
public class Weixinuserinforesult
{
<summary>
Micro-Credit User information
</summary>
Public Weixinuserinfo UserInfo {get; set;}
<summary>
Results
</summary>
public bool Result {get; set;}
<summary>
Error message
</summary>
Public weixinerrormsg errormsg {get; set;}
}
View Code
Weixinuser class:
Micro-Credit development notes-micro-letter Web login authorization, access to user information
Micro-Credit development notes-micro-letter Web login authorization, access to user information
public class Weixinuserinfo
{
<summary>
Unique identification of the user
</summary>
public string OpenID {get; set;}
<summary>
User Nickname
</summary>
public string Nickname {get; set;}
<summary>
The user's sex, the value of 1 o'clock is male, the value of 2 o'clock is female, the value of 0 o'clock is unknown
</summary>
public string Sex {get; set;}
<summary>
The province in which the user's personal data is filled
</summary>
public string Province {get; set;}
<summary>
The city where the ordinary user's personal data fills in
</summary>
public string City {get; set;}
<summary>
Countries, such as China for CN
</summary>
public string Country {get; set;}
<summary>
User Avatar, the last value represents the size of the square head (there are 0, 46, 64, 96, 132 value Optional, 0 represents 640*640 square avatar), the user does not have the Avatar when the item is empty
</summary>
public string Headimgurl {get; set;}
<summary>
User privileged information, JSON array, such as micro-SIM user (chinaunicom)
</summary>
Public string[] Privilege {get; set;}
}
View Code
All the pages, will inherit BasePage page, so easy to handle, inherit this page of other pages will not need to consider the issue of authentication.
public partial class BasePage:System.Web.UI.Page
{
Public BasePage ()
{
This. Page.load + = new EventHandler (Page_Load);
This. Page.unload + = new EventHandler (page_unload);
}
protected void Page_Load (object sender, EventArgs e)
{
Dowith ();
}

protected void Page_Unload (object sender, EventArgs e)
{
}
private void Dowith ()
{
User not logged in
if (BLL. Userinfomanager.instance (). GetUserID () <= 0)
{
Get configuration information for Appid,appsecret
String appId = system.configuration.configurationsettings.appsettings["AppId"];
String appsecret = system.configuration.configurationsettings.appsettings["secret"];
Core.weixinoauth Weixinoauth = new Weixinoauth ();
The code and state obtained after the first handshake of the micro-letter
String _code = Cmn.Request.Get ("code");
String _state = Cmn.Request.Get ("state");

if (_code = = "" _code = = "Authdeny")
{
if (_code = "")
{
Initiating authorization (first micro-letter handshake)
String _authurl = Weixinoauth.getweixincode (AppId, Appsecret, HttpContext.Current.Server.UrlEncode ( HttpContext.Current.Request.Url.ToString ()));
HttpContext.Current.Response.Redirect (_authurl, true);
}
Else
{//User cancels authorization
HttpContext.Current.Response.Redirect ("~/error.html", true);
}
}
Else
{
Get micro-letter Access_token (second micro-letter handshake)
Core.Model.WeiXinAccessTokenResult Modelresult = Weixinoauth.getweixinaccesstoken (AppId, Appsecret, _code);

Access to micro-mail user information (third micro-letter handshake)
Core.Model.WeiXinUserInfoResult _userinfo = Weixinoauth.getweixinuserinfo (ModelResult.SuccessResult.access_token, ModelResult.SuccessResult.openid);

User information (to determine if the user's micro-credit user information has been obtained)
if (_userinfo.result && _userinfo.userinfo.openid!= "")
{
Save the obtained user's micro-user information and save it to the database
}
Else
{
GameTradingByPublic.ExceptionLog.writeFile (2, "Get user OpenID failed");
}
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.