Android Development: Micro-Letter Authorization login and micro-credit sharing complete analysis _android

Source: Internet
Author: User
Tags openid

Objective

In the mobile internet wave, the network app has been shot dead on the beach, many companies want their own applications can have a set of account system, but many users do not necessarily buy: Why do I register your home application account? Micro-bo, micro-letter, QQ almost everyone in the mobile phone will be installed applications, so micro-letter, micro-BO, QQ said: Come, you can use my home account to log in to your home application, as long as you follow the OAUTH2.0 protocol standards on the line. So the third party social accounts have become a choice for many new applications, since Tencent's official micro-credit platform's online documentation is somewhat different from the latest SDK, and the log-related document structure is somewhat disordered, today I have some of my experiences here to sort out the official online documents of the micro-credit platform. At the same time, micro-letter sharing can expand the impact of their own app, so the micro-letter sharing function is also a lot of developers need the function, together in this, hope to be helpful to the fellow friends later.

Micro-Letter Login

The following part is excerpted from Tencent Open platform:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list& Verify=1&id=open1419317851&token=6bfe3acd2969037c7217667f24f8eeaf714e5113&lang=zh_cn

Authorization Process Description

Micro-letter OAuth2.0 authorized login to allow micro-users to use micro-letter identity Security Login to the Third-party application or Web site, in the micro-trust users authorized to log on to the OAuth2.0 of the third party application, the third party can obtain the user's interface call credentials (Access_token), through the Access_ Token can be used to invoke the authorization interface of the micro-trust platform, which can realize the basic open information of the micro-user and help the user realize the basic open function.

The OAuth2.0 authorization login currently supports the Authorization_code mode and is suitable for application authorization with server side. The overall process for this pattern is:

1. When a third party initiates a micro-letter authorization login request, the micro-trust user authorizes the third party to apply, the micro-letter will pull up the application or redirect to the third party website, and with the authorization temporary bill code parameter;

2. Through the code parameters plus AppID and Appsecret, through the API to exchange for Access_token;

3. Interface calls through Access_token to obtain user basic data resources or to help users achieve basic operations.

Get Access_token sequence diagram:

Note: If the developer needs to call the login interface, need to conduct a developer certification and make 300 ocean, the official online documentation says no fee, in fact, that is already the past, but the online documents are not updated and different.

The following is a step-by-turn explanation of the micro-letter authorization login process. All network requests are get requests.

1, access to temporary instrument code

2. Get Access_token & OpenID

3, check whether the Access_token is effective

4. Refresh or Renew Access_token

5. Access to micro-credit user Details

Get temporary Bill code

Top three arrows to the right

{ 
  //issuing authorization to apply for
  Final sendauth.req Req = new Sendauth.req ();
  Req.scope = "Snsapi_userinfo";
  Req.state = "Wechat_sdk_ micro-letter login, Share demo_test";
  Api.sendreq (req);
}

The two arrows to the left of the process are reflected in the code:

public void Onresp (Baseresp resp);//This callback interface is in Iwxapieventhandler

The returned data is RESP, which is an instance of SENDAUTH.RESP when requesting login authorization, and carries the following data:

    1. ERRORCODE:ERR_OK = 0 (user agrees); err_auth_denied =-4 (user denies authorization); err_user_cancel =-2 (user canceled)
    2. Code: User in exchange for Access_token code, valid only at Errcode 0 o'clock
    3. State: A flag used by a third party program to identify the uniqueness of its request when invoked by a third party program, sendreq by a micro-letter terminal, and the state string cannot be longer than 1K
    4. Lang: micro-letter Client Current language
    5. Country: Micro-Credit Client current country

All of the above data exists in the Sendauth.resp Resp object as a static string.

Note: When using micro-letters to provide the latest sdk/library, some of the data above is not present, and the micro-credit open platform documentation and APIs and SDK are not synchronized. Readers can use the bottom of the micro-letter login to share the demo in the author's use of the JAR package construction project.

Get Access_token & OpenID

The last arrow to the right indicates: Use the resulting code to get Access_token,openid, which is:
Https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type= Authorization_code

Note: Micro-letter interface links are using SSL security links, ordinary httpclient access will cause application crashes or errors, detailed methods please download the bottom of the micro-letter login, share demo code

Parameter description

    • AppID: Application of unique identification, after the micro-credit open platform submitted application audit passed
    • Secret: Application of key Appsecret, after the micro-credit open platform submitted application audit passed
    • Code: Fill in the first step to get the code parameter
    • Grant_type: Fixed value, fill Authorization_code

The bottom left arrow indicates that using code to access the data returned by the link, JSON carries the following data:

    • Access_token: Interface Call voucher
    • Expires_in:access_token is normally valid for 7200 (seconds), or two hours.
    • Refresh_token: User Refresh Access_token
    • OpenID: Authorized User Unique identification
    • Scope: User-authorized scope, separated by commas (,)

Check if Access_token is valid

Since Access_token is valid for two hours, it is a good idea to perform a check before proceeding next, with the following interface:
Https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID

The incoming parameters are Accesss_token and OpenID.

The JSON returned when Access_token is valid is:

{ 
"Errcode": 0, "errmsg": "OK"
}

The return data at expiration is:

{ 
"Errcode": 40003, "errmsg": "Invalid OpenID"
}

If the Access_token is valid, skip the next step and refresh or renew the Access_token when it fails.

Refresh or Renew Access_token

Interface description

Access_token is the invocation voucher that invokes the authorization relationship interface, because Access_token is short for a period of time (currently 2 hours), and can be refreshed using Refresh_token after the Access_token timeout, Access_ There are two types of token refresh results:

1. If the Access_token has timed out, then the Refresh_token will get a new access_token, the new timeout time;

2. If the Access_token does not time out, then the Refresh_token will not change the Access_token, but the timeout will be refreshed, equivalent to the renewal of Access_token.

Refresh_token has a longer period of validity (30 days), and when the Refresh_token expires, users need to be authorized again.

The Refresh Accesstoken interface is:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token= Refresh_token

Parameter description:

    • AppID: Applying unique identities
    • Grant_type: Fixed value, fill Refresh_token
    • Refresh_token: Fill in the value of the Refresh_token obtained before

The JSON data returned is:

    • Access_token: Interface Call voucher
    • Expires_in:access_token interface Call voucher timeout time, in seconds
    • Refresh_token: User Refresh Access_token
    • OpenID: Authorized User Unique identification
    • Scope: User-authorized scope, separated by commas (,)

Get micro-Credit user Details

After acquiring the Access_token,openid, it can be used to obtain more user information, such as micro-letter nickname, Avatar, gender, etc. The interface is:
Https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

The data that can be captured by JSON is:

    • OpenID: Common User ID, unique to current developer account
    • Nickname: Ordinary user Nickname
    • Sex: Average user sex, 1 is male, 2 is female
    • Province: The province where the ordinary user's personal data is filled
    • City: Ordinary user's personal data fill in the cities
    • Country: Country, such as China for CN
    • Headimgurl: User avatar, the last value represents the size of the square head (there are 0, 46, 64, 96, 132 value optional, 0 for the 640*640 square avatar), the user does not have the Avatar when the item is empty
    • Privilege: User privileged information, JSON array, such as micro-SIM user (chinaunicom)
    • Unionid: User uniform identity. For an application under a micro-credit open platform account, the Unionid of the same user is unique.

Micro-Credit official recommendations:

It is better for developers to keep Unionid information so that users can communicate with each other in the future.

The process of the micro-mail login is over, and the developers need to upload those user information to their app server.

Micro-letter Sharing

1, micro-letter sharing is divided into micro-trust friends to share, friends circle to share, of course, there is also a collection is shared with the interface, without authorization login can invoke the sharing interface.

2, because friends to share, friend Circle Sharing and collection is only a parameter difference, so the following only talk about friend sharing, the specific can download the bottom of the micro-letter login, share demo source to view.

3, micro-letter can share content including, pure text, pictures, links, music, video, App,emoji expression and so on.

Micro-Credit Sharing process

1. Create a new WXAPI package in your project, and create a new wxentryactivity, inherit activity, or other activity (these two steps are necessary, as mentioned in the micro-letter development document), as described in:
Https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id= 1417751808&token=&lang=zh_cn

2, and in the manifest file, add the exported property, set to True.

3, implement a Iwxapieventhandler interface.

The request sent by the micro-mail will be recalled to the Onreq method, and the response to the micro-letter request will be recalled to the Onresp method

The Handleintent method that the intent received in wxentryactivity and the object that implements the Iwxapieventhandler interface is passed to the Iwxapi interface, as shown in the following example:

Api.handleintent (Getinent (), this);

When a micro-letter sends a request to your application, a callback is made via the Onreq method of the Iwxapieventhandler interface, and similarly, the response of the application request Micro-letter is passed through the ONRESP callback.

Attention

If you need to confuse the code, in order to ensure normal use of the SDK, you need to add the following two lines of configuration to the Proguard.cfg:

-keep class com.tencent.mm.sdk.** { 
 *; 
 }

Micro-credit sharing detailed code flow is:

Iwxapi API = Wxapifactory.createwxapi (this, app_id, false);//Incoming request to AppID, get a Iwxapi instance
Api.registerapp (app_id) //app register to the micro-letter list, I do not know what this means, have to know, please tell me, thank you!

//Start sharing plain text to friends
Wxtextobject textobj = new Wxtextobject ();
Textobj.text = text;

Initializes a Wxmediamessage object with the Wxtextobject object
wxmediamessage msg = new Wxmediamessage ();
Msg.mediaobject = textobj;

When sending a text type message, the Title field does not work
//Msg.title = "would be ignored";
Msg.title = "Share text title";
msg.description = text;

Construct a Req
sendmessagetowx.req Req = new Sendmessagetowx.req ();
Req.transaction = buildtransaction ("text"); The transaction field is used to uniquely identify a request
req.message = msg;

Req.scene = sendmessagetowx.req.wxscenetimeline;//to send the scene for the circle of friends, this representative to share to the circle of friends
//Req.scene = Sendmessagetowx.req.wxscenesession;//said to send the scene for the friend dialogue, this delegate share to friends
//Req.scene = sendmessagetowx.req.wxscenefavorite;//represents the sending scene for the collection, which is added to the micro-letter collection
//Call API interface to send data to the micro-letter 
Api.sendreq (REQ);

It basically shows a scene to share plain text to a friend, and if you need to share a circle of friends, you just need to change the Req.scene field values.

1, which Iwxapi.registerapp (app_id) is an official demo in a line of code, that is, to register the APP to the micro-letter list, I do not know what the use of the so-called micro-letter list appears in? After this line of code is deleted, you can still obtain login authorization and realize sharing functions. Please tell me if you know, thank you!

2, at present I encountered can not share the online picture wximageobject problem, share the online picture when the sharing interface in the upper right corner "send" button gray, can not click the situation, hope to share a successful friend told me, thank you! The problem is shown below

To share links, pictures, music, videos, etc., you need to change the Wxtextobject object to the corresponding Obj object. Please download the details below the micro-letter login, share demo.

Postscript

Since the micro-letter official demo does not provide a code example for the micro-letter login, share of the code is complete, but the sharing of online pictures in my code here but also the problem, so the author will own some experience and encountered the pit summed up here, including micro-letter third party login, micro-letter sharing content, I hope to help. I also hope that the author mentioned in the text of the problem has enthusiastic people can answer

1, register to the micro-letter list What is the use, micro-letter list where you can see
iwxapi.registerapp (app_id);
2, why I can not use the following code to share online picture
wximageobject imgobj = new Wximageobject ();
Imgobj.imageurl = imgurl;//online picture link

wxmediamessage msg = new Wxmediamessage ();
Msg.mediaobject = imgobj;

Bitmap bmp = Bitmapfactory.decodestream (new URL (URL). OpenStream ());
Bitmap thumbbmp = Bitmap.createscaledbitmap (BMP, Thumb_size, thumb_size, true);
Bmp.recycle ();
Msg.thumbdata = Util.bmptobytearray (Thumbbmp, true);

Sendmessagetowx.req Req = new Sendmessagetowx.req ();
Req.transaction = Buildtransaction ("img");
Req.message = msg;
Req.scene = istimelinecb.ischecked ()? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
Api.sendreq (req);

Someone recently showed me that the generated apk is not working correctly. To explain here:

Demo source generated by the APK is not normal operation of the reason is: in the micro-credit open platform to add applications, package name, application signature, app_id is bound. Your signature apk does not work, demo code for reference only Exchange.

Demo Source Download: Source Demo

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.