C # Implementation of micro-letter Web page Authorization Operation logic Encapsulation Example _c# tutorial

Source: Internet
Author: User
Tags class definition openid

This paper illustrates the logic encapsulation of the authorization operation of the micro-letter Web page implemented by C #. Share to everyone for your reference, specific as follows:

First, the micro-letter Web page Authorized Login

Premise:

1. The interface permission has been acquired, if the test account has already been authorized

2. Configure the interface's authorized domain name

More instructions can refer to the Square Times studio: http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html

or the official website api:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

Steps:

1. Users agree to authorize, get code

2. According to code to obtain Access_token and current operating user's OpenID, Unionid

3. Obtain basic user information based on OpenID (if required)

Note: If you want to use a sweep on the website, authorize login, you can speak _oauth. Getcodeurl () authorization address to generate a two-dimensional code to use

C # encapsulated micro-letter Web page Authorization login usages:

string AppID = "Wx145b4a8fd07b24e8";
String appsecrect = "fe6951dcb99772411c42f724b1336065";
String Redirect_url = "The callback address under the configuration domain name";
Oauthmanage _oauth = null; <summary>///Controller Constructor///</summary> public Usercontroller () {_oauth = new Oauthmanage (AppID, Appsecrect
, Redirect_url);
  ///<summary>///Authorized login///</summary>///<returns></returns> public ActionResult Authlogin () { Viewbag.url = _oauth.
  Getcodeurl ();
return View (); 
///<summary>///callback processing///</summary>///<returns></returns> public actionresult oauthhandle ()
  {String result = ' "; Registers event handling _oauth.
    OnError = (e) => {string msg = "";
    Exception inner = e; while (inner!= null) {msg = inner.
      message; Inner = inner.
    innerexception;
    result = msg;
  Logoperate.write (msg);
  }; _oauth.
    Ongettokensuccess = (token) => {result = = "<br/>"; result = token.
  toJSONString ();
  }; _oauth. Ongetuserinfosuccess = (user) => {result = "<br/>"; result = user.
  toJSONString ();
  }; The second step is _oauth.
  Getaccess_token (); The third step is _oauth.
  GetUserInfo ();
  Display results viewbag.msg = result;
return View ();

 }

Encapsulate code class definition:

namespace Wxpackage {///<summary>///Web page Authorization logic processing,///processing three-step operation, processing successful, return user basic information///</summary> public cl Ass Oauthmanage {#region basic information definition///<summary>///Public number unique identification///</summary> private Strin
    G AppID;
    <summary>///Public number Appsecret///</summary> private string secret;
    <summary>///callback URL address///</summary> private string Redirect_uri; 
    <summary>///access to micro-credit user basic information Use Snsapi_userinfo mode///If you use silent authorization, you cannot get user profile but you can get OpenID///</summary>
    private string scope; Public Oauthmanage (String AppID, String Appsecret, String Redirect_uri, bool Isuserinfo = true) {This.appid = a
      Ppid
      This.secret = Appsecret;
      This.redirect_uri = Redirect_uri; This.scope = Isuserinfo?
    "Snsapi_userinfo": "Snsapi_base"; #endregion #region Request process Information///<summary>///The code value obtained in the first step///</summary> public stri Ng Code {get; set;} <summary>///the Access_token and related data obtained in the second step///</summary> public oauthaccess_token tokendata = nul
    L #endregion #region Event definition///<summary>///triggers the///</summary> public action<exce When an exception is handled
    Ption> OnError = null; <summary>///When getting accesstoken success is triggering///</summary> public action<oauthaccess_token> Ongett
    Okensuccess = null; <summary>///triggers///</summary> public action<oauthuser> When a successful user information is obtained ongetuserinfosuccess
    = NULL;
    #endregion #region The second step, callback processing///<summary>///The second step, through code in exchange for Web page authorization Access_token///</summary> public void Getaccess_token () {try {//1. Processing jump this.
        Code = reqhelper.getstring ("code"); if (string. IsNullOrEmpty (this.
        Code)) throw new Exception ("Get code parameter failure or user forbid authorization to get basic information"); 1. Send get access_token request string url = Getaccess_tokenurl();
        string result = Nethelper.get (URL);
        2. Resolution of corresponding results Tokendata = jsonconvert.deserializeobject<oauthaccess_token> (result);
        if (Tokendata = = null) throw new Exception ("The deserialization result fails, the return is:" + results);
      3. Obtain success if (ongettokensuccess!= null) ongettokensuccess (tokendata);
      catch (Exception ex) {Error ("Step two, through code in exchange for Web page Authorization Access_token exception", ex); }///<summary>///refresh current Access_token///</summary> public Oauthaccess_token Refreshacce
        Ss_token () {try {//1. send request String url = Getreferesh_tokenurl ();
        string result = Nethelper.get (URL);
        2. Analytical results Oauthaccess_token Token = jsonconvert.deserializeobject<oauthaccess_token> (result);
        if (token = = null) throw new Exception ("deserialization result failed, return content:" + results);
      return token; The catch (Exception ex) {Error ("Refresh current Access_token failed", ex);
      return null; #endregion #region Step three, get user basic information///<summary>///step Three, get basic information///</summary> PU
        Blic void GetUserInfo () {try {//1. Send get request string url = Getuserinfourl ();
        string result = Nethelper.get (URL);
        2. Analytic results Oauthuser user = jsonconvert.deserializeobject<oauthuser> (result);
        if (user = null) throw new Exception ("deserialization result failed, return content:" + results);
      3. Obtain success if (ongetuserinfosuccess!= null) ongetuserinfosuccess (user);
      catch (Exception ex) {Error ("Third step, get user basic information exception", ex); }} #endregion #region static method///<summary>///Verify that authorization credentials are valid///</summary>///&LT;PA Ram Name= "Access_token" >access_token</param>///<param name= "OpenID" > User's Openid</param for current public number >///<returns></returns> public static bool Checkwebaccess_token (sTring Access_token, String OpenID) {try {string url = string.
        Format ("Https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}", Access_token, OpenID);
        string result = Nethelper.get (URL);
        Jobject obj = jobject.parse (result);
        int errcode = (int) obj["Errcode"];
      return Errcode = = 0; The catch (Exception ex) {throw new Exception ("," + Ex.)
      message); #endregion #region Get request connection///<summary>///get code URL address///</summary>///& Lt;returns></returns> public String Getcodeurl () {string url = string. Format ("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type= Code&scope={2}&state=state#wechat_redirect ", This.appid, Securityhelper.urlencode (This.redirect_ur
      i), this.scope);
    return URL; }///<summary>///get Access_tokenURL address///</summary>///<returns></returns> private String Getaccess_tokenurl () { String url = string. Format ("Https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type =authorization_code ", This.appid, This.secret, this.
      Code);
    return URL; ///<summary>///Get refresh Accesstoke address///</summary>///<returns></returns> p Rivate string Getreferesh_tokenurl () {string url = string. Format ("Https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_ Token={1} ", This.appid, this.
      Tokendata.refresh_token);
    return URL; ///<summary>///Get user profile address///</summary>///<returns></returns> Private String Getuserinfourl () {string url = string. Format ("https://api.weixin.qq.com/sns/userinfo?access_token={0}&AMP;OPENID={1}&AMP;LANG=ZH_CN ", this. Tokendata.access_token, this.
      Tokendata.openid);
    return URL; #endregion private void Error (String msg, Exception inner) {if (this. OnError!= null) {this.
      OnError (New Exception (MSG, inner));  Get user profile///</summary> public class Oauthuser {public string after///<summary>///authorization
    OpenID {get; set;}
    public string Nickname {get; set;}
    public int sex {get; set;}
    public string Province {get; set;}
    public string City {get; set;}
    public string Country {get; set;}
    public string Headimgurl {get; set;}
    <summary>///user privileged information, JSON array///</summary> public jarray privilege {get; set;}
  public string Unionid {get; set;} ///<summary>///get Access_token or refresh the returned data object///</summary> public class Oauthaccess_token {PU
    Blic string Access_token {get; set;} PubLic int expires_in {get; set;}
    public string Refresh_token {get; set;}  <summary>///users///attention to the unique identification of the current public number will be generated after the return of the public number of the page will also produce///</summary> common string OpenID { Get Set
    public string Scope {get; set;} <summary>///The Unionid of the current user, only after the user binds the public number to the microblogging open platform account///</summary> public string Unionid {get; s Et

 }
  }
}

Read more about C # Interested readers can view the site topics: "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Data structure and algorithm tutorial", "C # object-oriented Program design Introductory Course" and "C # programming Thread Usage Skill Summary"

I hope this article will help you with C # programming.

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.