Developing Android to Realize Tripartite Login of Microblog(1)
This article describes three ways to realize the tripartite login of microblog. In fact, they are three ways. But there is only one slight difference between them, that is, the method names invoked before entering the authorization page are different.
1. SSO single sign-on authorization, calling this method can only be achieved on the premise that you have installed the Sina Weibo APP on your mobile phone.
2. Web page login authorization, this method will jump out of a micro-blog login Web page, so as to achieve login.
3. all in one mode authorization, which will decide whether to use sso authorization or web authorization according to whether the mobile phone installs micro-blog client or not. If there is a micro-blog client installed, the micro-blog client authorization will be invoked, otherwise the Web page authorization will be invoked.
The following is the specific implementation process:
1. Authorization section (Obtaining an Oauth2AccessToken object in the code)
1. APP key and App secret are applied for on Sina Weibo Open Platform. The specific steps are omitted. It is not only to fill in some application information, but also very easy to apply for (the developer account of unregistered Sina may need to register an account first). Here is the interface after successful application.
http://open.weibo.com/
2. Fill in the "Basic Information" directory in the interface above. Android Information such as package name (the package name of your project), Android signature (you need to download the signature tool to generate the corresponding signature of the project) and click Save
Then add the callback page (http://api.weibo.com/oauth2/default.html) under Advanced Information, and click Submit
If run test When login account is not registered application account, then you need to add test account under "test information", and then click Save
3. Download SDK address: http://open.weibo.com/wiki/SDK
4. Create a new jniLibs folder (don't misspell) under the main folder of the project. Copy all the folders under the libs folder in SDK to the jnilib folder of the project. The Weibo SDK Core_3.1.4.jar package is introduced into the project.
5. Adding permissions
7. Three objects are required in Java code
Initialization object
8. Define an implementation class for WeiBoAuthListener, which is required regardless of the authorization method mentioned above.
9. The following are the methods invoked by various authorization modes (as you can see, the main difference among the three login modes is that the ssohandler object invocation method is different).
Note: If you are using web authorization, you need to declare the following activities in Android Manifest. XML
10. An easy step to take, rewrite the onActivityResult method, or you won't be able to call back the method
In this way, the authorization part is fully implemented.
2. Obtain the basic information of the user (Obtain the basic information of the user through the Oauth2AccessToken object obtained above)
11. To get information, weibosdk in SDK should be introduced into the project as a library (I quoted its jar package directly, which proved to be possible).
Declare a variable first
Then getUserInfo() is removed from the onComplete callback method of weiboAuthListener above; the comment on that code is removed. The getUserInfo() method is implemented as follows.
In this way, we can get the basic information of users!
Information in the User class can be consulted: http://open.weibo.com/wiki/2/users/show
This demo is completed with reference to Word documents 6.1 and 7.1 under the New Documents folder in SDK.
Demo Download Address: http://download.csdn.net/detail/highboys/9597488
Developing Android to Realize Tripartite Login of Microblog(2)
Friends who have done third-party login on Sina Weibo know that their official documents are really bad, and adding new applications is also troublesome. I also read the document, while looking at demo, scrambling to achieve third-party login function. Today I share with you a complete development process, from the application developer account, to the integration of SDK, to code writing. ps: The SDK version I used was Weibo SDK Core_3.1.2
Step 1: Apply for Developer Account, Official Website http://open.weibo.com
Log in or register Sina Weibo account
Then create a new application. When you create it, you should pay attention to several points:
Get APPID, my application - > application information - > basic information
My Application - > Application Information - > Basic Information
The package name refers to the contents of the package attribute in the AndroidManifest.xml file.
Signatures must be generated through the official MD5 signature tool, but Baidu Search, I also have a link here. http://pan.baidu.com/s/1qWlD1LE
It's about this long. Just fill in the Android signature column on the official website against the signature.
Click on my application - > application information - > advanced information, and fill in the callback address. This is the address that will be invoked after the authorization is successful. It will be used in subsequent coding. It must be consistent. You can use http://www.sina.com.
Add a test account.
Step 2: Integrating SDK,
Download the latest SDK files on the official website.
Or use what I've provided here.
http://pan.baidu.com/s/1sjFxEbz
Copy six folders under the directory weibo_android_sdk-master libs to the libs file of the project.
Copy Weibo SDK Core_3.1.2.jar to libs file under weibo_android_sdk-master directory
Then select weiboSDK Core_3.1.2. jar, right-click Build Path - > Add to Build Path
So far, the integration has been half successful.
Modify the AndroidManifest.xml file and add the following code
<activity
android:name="com.sina.weibo.sdk.component.WeiboSdkBrowser"
android:configChanges="keyboardHidden|orientation"
android:exported="false"
android:windowSoftInputMode="adjustResize" >
</activity>
<service
android:name="com.sina.weibo.sdk.net.DownloadService"
android:exported="false" >
</service>
Add permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
So SDK is integrated.
Step 3: Coding
I mainly refer to the official demo to write, the key is three java files
LoginActivity, which centrally calls the class of Sina Weibo API, realizes the functions of third party authorization, login, exit and display user information when login.
package com.example.thirdpartyloginafc;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
public class LoginActivity extends Activity implements OnClickListener {
private AuthInfo mAuthInfo;
private Button btnweibo;
private Button btnlogout;
private TextView tv;
private String nickname="";
/** Encapsulated "access_token", "expires_in", "refresh_token" and provided their management functions.*/
private Oauth2AccessToken mAccessToken;
/** Note: SsoHandler is valid only if SDK supports SSO.*/
private SsoHandler mSsoHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initweibologin();
initViews();
initEvents();
initData();
}
private void initData() {
// TODO Auto-generated method stub
//Read the last saved AccessToken and other information from Shared Preferences.
//AccessToken is not available when this application is first launched
mAccessToken = AccessTokenKeeper.readAccessToken(this);
if (mAccessToken.isSessionValid()) {
updateTokenView(true);
}
}
private void initViews() {
btnweibo = (Button) findViewById(R.id.btn_weibo_login);
btnlogout = (Button) findViewById(R.id.btnlogout);
tv = (TextView) findViewById(R.id.content);
//Get Token View and make the content of the prompt View scrollable (small screen may not be fully displayed)
tv.setMovementMethod(new ScrollingMovementMethod());
}
private void initEvents() {
btnweibo.setOnClickListener(this);
btnlogout.setOnClickListener(this);
}
/**
* Initialization of Microblog Authorization
*/
private void initweibologin() {
// TODO Auto-generated method stub
//Initialize authorization class objects and save application information
mAuthInfo = new AuthInfo(this, Constants.APP_KEY,
Constants.REDIRECT_URL, Constants.SCOPE);
mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);
}
/**
* When SSO authorizes Activity to exit, the function is called.
*
* @see {@link Activity#onActivityResult}
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//SSO Authorized Callback
//Important: Activity that initiates SSO landing must rewrite onActivityResults
if (mSsoHandler != null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_weibo_login://SSO Authorization, ALL IN ONE
//If a microblog client is installed on the mobile phone, client authorization is used, and if not, web authorization is used.
mSsoHandler.authorize(new AuthListener());
break;
case R.id.btnlogout://User logout
nickname = "";
AccessTokenKeeper.clear(getApplicationContext());
mAccessToken = new Oauth2AccessToken();
updateTokenView(false);
break;
default:
break;
}
}
/**
* Microblog Authentication Authorization Callback Class. 1. SSO authorization requires{@link #onActivityResult} Call in
* {@link SsoHandler#authorizeCallBack} After that, the callback will be executed. 2. Non-SSO
* When authorization ends, the callback is executed. When the authorization is successful, please save the access_token, expires_in, uid and other information to
* SharedPreferences Medium.
*/
class AuthListener implements WeiboAuthListener {
@Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(LoginActivity.this, "Cancellation of authorization", Toast.LENGTH_LONG)
.show();
}
@Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
//Analysis of Token from Bundle
mAccessToken = Oauth2AccessToken.parseAccessToken(values);
if (mAccessToken.isSessionValid()) {
nickname = "User name:"
+ String.valueOf(values
.get("com.sina.weibo.intent.extra.NICK_NAME"));
//Display Token
updateTokenView(false);
//Save Token to Shared Preferences
AccessTokenKeeper.writeAccessToken(LoginActivity.this,
mAccessToken);
Toast.makeText(LoginActivity.this, "Authorized success", Toast.LENGTH_SHORT)
.show();
// Toast.makeText(
// LoginActivity.this,
//"Head Address:"
// + String.valueOf(values
// .get("com.sina.weibo.intent.extra.USER_ICON")),
// Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this, nickname, Toast.LENGTH_LONG)
.show();
} else {
//In the following cases, you will receive Code:
//1. When you have not registered the package name and signature of the application on the platform;
//2. When your registered application package name and signature are incorrect;
//3. When the package name and signature registered on the platform do not match the package name and signature of the application you are currently testing.
String code = values.getString("code");
String message = "privilege grant failed";
if (!TextUtils.isEmpty(code)) {
message = message + "\nObtained the code: " + code;
}
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onWeiboException(WeiboException e) {
// TODO Auto-generated method stub
Toast.makeText(LoginActivity.this,
"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
/**
* Display current Token information.
*
* @param hasExisted
* Whether token information already exists in the configuration file and is legal
*/
private void updateTokenView(boolean hasExisted) {
String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
.format(new java.util.Date(mAccessToken.getExpiresTime()));
String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
tv.setText(String.format(format, mAccessToken.getToken(), date));
String message = String.format(format, mAccessToken.getToken(), date);
if (hasExisted) {
message = getString(R.string.weibosdk_demo_token_has_existed)
+ "\n" + message;
}
message += "\n" + nickname;
tv.setText(message);
}
}
package com.example.thirdpartyloginafc;
/*
* Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
/**
* This class defines the parameters needed for authorization of microblog.
*
* @author SINA
* @since 2013-10-07
*/
public class AccessTokenKeeper {
private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
private static final String KEY_UID = "uid";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_EXPIRES_IN = "expires_in";
private static final String KEY_REFRESH_TOKEN = "refresh_token";
/**
* Save the Token object to SharedPreferences.
*
* @param context
* Application context environment
* @param token
* Token object
*/
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_APPEND);
Editor editor = pref.edit();
editor.putString(KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
editor.commit();
}
/**
* Read Token information from Shared Preferences.
*
* @param context
* Application context environment
*
* @return Return Token object
*/
public static Oauth2AccessToken readAccessToken(Context context) {
if (null == context) {
return null;
}
Oauth2AccessToken token = new Oauth2AccessToken();
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_APPEND);
token.setUid(pref.getString(KEY_UID, ""));
token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
token.setRefreshToken(pref.getString(KEY_REFRESH_TOKEN, ""));
token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
return token;
}
/**
* Empty Token information in Shared Preferences.
*
* @param context
* Application context environment
*/
public static void clear(Context context) {
if (null == context) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_APPEND);
Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}
package com.example.thirdpartyloginafc;
public class Constants {
public static final String APP_KEY = "Own id";
public static final String REDIRECT_URL = "Callback address corresponding to web page;
public static final String SCOPE = "email,direct_messages_read,direct_messages_write,"
+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
+ "follow_app_official_microblog," + "invitation_write";
}
Operation result
Authorized success
Officially, there are three ways of login, the first is through the client, the second is through the web, the third is to try to login through the client, if there is no client installed, then through the web, the third way is used here.
The code for this example: http://pan.baidu.com/s/1nttlgt7
After importing the project, remember to modify the APP_KEY and REDIRECT_URL in Constants. If you have any questions, please communicate!!
Development of sdk and Address of Development Help Documents on Microblog
https://github.com/sinaweibosdk/weibo_android_sdk
Android implements QQ third party login
Android Implementing QQ third party login
QQ third-party login is needed in the project. After some efforts, it has been written out. Now summarize the following, in order to avoid forgetting later, it would be better to help other children's shoes.
The first thing is to download SDK and DEMO.
http://wiki.open.qq.com/wiki/mobile/SDK Download
This article is my own integrated simple DEMO.
Let's look at the picture first.
Principle: We need to use QQ to login our application, not without registration, but we are registering for users in the background, but users do not know that registration needs a unique identity, the combination of letters and numbers above is the only identity we want to obtain: OpenID.
Follow the code.
First, we'll load the open_sdk.jar and mta-sdk-1.00.jar packages. By the way, let's look at the classes I've used altogether.
Among them, AppConstant is used to place the APPID, because other third-party logins may be introduced to facilitate management, so create such a class. Util is a processing class that retrieves pictures from the Internet according to the path
Well, get to the point.
First, two definitions in AndroidManifest.xml are not possible if they are not defined
Then there are two permissions
Next is the layout file, activity_main.xml login button, to get the textview of the avatar, nickname, openid
Then MainActivity
The figure above shows the return LOG of login Q
Above is our LOG returned from UserInfo provided by Tencent.
Then AppConstant. Java
Then Util.java
Here's all the code. We get OpenID, which is the key to the unique identity. Then we can see what information is needed for the interface that needs to be logged on in the project to get it.
qq official document reference
http://wiki.open.qq.com/wiki/Create and Configure Engineering
http://wiki.open.qq.com/wiki/Create instances and implement callbacks
http://wiki.open.qq.com/wiki/QQ login and logout
Http://wiki.open.qq.com/wiki/mobile/SDK download address
Android Wechat Third Party Login
These two days, it solved the problem of authorized login of the third party of Wechat. As a novice, it is also a bitter tear to think about. I think, I will share with you the pit I encountered, so that novices can avoid such problems as mine smoothly.
Step 1 Wechat Developer Platform
The solution I started with was to go. Wechat Developer Platform Look at the API documentation.
The main meaning of this API document is three points:
1. You have to download these things.( Download links One is his sample code and the other is his signature generation tool.
2. If your own APP wants to be authorized by the third party of Wechat, you have to apply for an APPID, which is a code assigned to us by Wechat. Of course, Wechat is not a free service for you. In order to get this third-party authorized function, you have to pay 300 yuan to Wechat. After applying for this authorization, you need to fill in an application package name and an application signature.
Application package name
Application signature
Use the signature generation tool, enter the package name, and query the application signature
3. Then open DEMO
WXEntry Activity is our most important concern.
1
2
3
4
5
|
//
When a wechat sends a request to a third party application, it calls back to this method.
@Override
public void onReq(BaseReq
req) {
//
TODO
}
|
This onResp method is automatically invoked when you click on the authorized login interface, so we can get the required token from it. Note that andorid is called token, ios is called code, not because of the sdk version, which needs to be noted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//
The response of a third-party application to a request sent to Wechat after processing is called back to this method.
@Override
public void onResp(BaseResp
resp) {
int result
= 0;
switch (resp.errCode)
{
case BaseResp.ErrCode.ERR_OK:
result
= R.string.errcode_success;
/* Get token*/
SendAuth.Resp
sendResp = (SendAuth.Resp) resp;
String
code = sendResp.token;
Log.d("Tag", "code\t" +
code);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result
= R.string.errcode_cancel;
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result
= R.string.errcode_deny;
break;
default:
result
= R.string.errcode_unknown;
break;
}
|
Replace APP_ID with a legitimate appId for your application from the official website
1
2
3
4
|
public class Constants
{
//
Replace APP_ID with a legitimate appId for your application from the official website
public static final
String APP_ID = "wx77777";
}
|
1
2
3
4
5
6
7
|
//
IWX API is an open API interface for third-party app and wechat Communications
private IWXAPI
api;
final
SendAuth.Req req = new SendAuth.Req();
req.scope
= "snsapi_userinfo";
req.state
= "wechat_sdk_demo_test";
// Send Authorized Landing Request
api.sendReq(req);
|
This step is to ask for code with Wechat. After executing this code. Wechat calls the onResp() method in the WXEntityActivity class just now. And return the code. See the code above. After you get the code, you can get access_token through the code.
Request the following link for access_token:
This step and Wechat communication access_token is the normal access link. Use httpClient instead of onReq(), the way to communicate with Wechat as mentioned in the Access Guide, and then use access_token. You can call the interface to get the user's basic information. The access guide for specific return parameters and what is said is very clear. So far, the authorization of Wechat has been basically successful.
Here, we will add Custom debug keystore. The debug keystore above will not communicate with Wechat.
And the keystore we added also meets some specifications, so we need to change it.
But pay attention to debug keystore in the development process.
Step 2 How Android studio generates keystore files
The first step is to create a signature file
Step 2 Fill in the Signature Parameters
The third step is to select the type of construction
Step 4 View Generating the apk file
Step 3 How Android studio locates keystore files
When running Weichat Sharing Demo and Sina Weibo Sharing Demo, debug.keystore in Demo needs to be modified to run authorization and sharing.
In Android development, the tools used are Eclispse and Android Studio. Among them, the use of Eclipse to modify the debug.keystore way Sina Weibo documents are introduced, in Eclipse click "Windows - > Preferences - > Android - > Build", in the right "Custom debug keystore" to select the Demo debug.keystore.
The approach in Android Studio is the application module of Modules in Project Structure. Then select Signing, click on the "+" number, call it "debug", and in "Store File", select debug.keystore in Demo, as shown below.
Then select "Build Types" in "Signing Config" in "debug" and select "debug" as configured above, as shown below.
Click "OK" and recompile it.
After the above configuration is completed, it will automatically be generated in android {} in build.gradle in the project module.
1
2
3
4
5
|
signingConfigs {
debug {
StorFile file('.keystore file path')
}
}
|
And generated in buildTypes
1
2
3
|
debug {
signingConfig signingConfigs.debug
}
|
Of course, you can write the above configuration in build.gradle without the interface configuration, and it's OK too.
Step 4 Get the signature and fill it in on the Wechat Developer Platform
Next, the project located in the jks file is burned and written into the program, and then the MD code of the signature tool is filled in to the Wechat Developer Platform, and the third party authorization can be invoked to login.
![]() |
![]() |
Effectiveness Map ___________
Reference link:
Wechat Authorized Login to Access Third Party App (Step Summary) Android
Android Studio modifies debug.keystore
Android Studio Signature Packing Process Diagram
Need to refer to the following website: android access to Wechat
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417751808&token=&lang=zh_CN
Mobile Application Wechat Login Development Guide
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=&lang=zh_CN
Authorized post-interface invocation (UnionID)
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317853&token=&lang=zh_CN