第三方qq登录

51 篇文章 0 订阅

使用的sdk版本:  V2.2.2(发布日期:2014.3.17)

因为,开发SDK的版本更新比较快,阅读的童鞋注意点吧。


开工前期的准备:

        1.建议你首先去下载最新的SDK,那里面除了有案例外,还有必须的jar包。

         2.最好在qq的开发平台自己注册个账号,那样移植起来更容易点。

给个链接吧:

        下载


配置清单:

       1.添加权限:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <uses-permission android:name="android.permission.INTERNET" />  
  2.    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  

      2.添加活动:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <activity  
  2.             android:name="com.tencent.tauth.AuthActivity"  
  3.             android:launchMode="singleTask"  
  4.             android:noHistory="true" >  
  5.             <intent-filter>  
  6.                 <action android:name="android.intent.action.VIEW" />  
  7.   
  8.                 <category android:name="android.intent.category.DEFAULT" />  
  9.                 <category android:name="android.intent.category.BROWSABLE" />  
  10.   
  11.                 <data android:scheme="tencent222222" /> <!-- 100380359 100381104 222222 -->  
  12.             </intent-filter>  
  13.         </activity>  
  14.         <activity  
  15.             android:name="com.tencent.connect.common.AssistActivity"  
  16.             android:screenOrientation="portrait"  
  17.             android:theme="@android:style/Theme.Translucent.NoTitleBar" />  
      在tencent后面添加自己的应用id,222222是腾讯给的专用测试id。


顺便提醒一句,在这个版本中要导入两个jar包。


布局:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/user_nickname"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="昵称" />  
  12.   
  13.     <ImageView  
  14.         android:id="@+id/user_logo"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content" />  
  17.   
  18.     <Button  
  19.         android:id="@+id/new_login_btn"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="登录" />  
  23.   
  24.     <TextView  
  25.         android:id="@+id/user_callback"  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:text="返回消息" />  

活动的详细代码:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /**  
  2.  * 测试qq第三方登录功能  
  3.  *   
  4.  */  
  5. public class TestQQ extends Activity implements OnClickListener {  
  6.     private TextView mUserInfo;  
  7.     private ImageView mUserLogo;  
  8.     private Button mNewLoginButton;  
  9.     private TextView backInfo;  
  10.   
  11.     private UserInfo mInfo;  
  12.     private Tencent mTencent;  
  13.     public QQAuth mQQAuth;  
  14.     // 申请的id  
  15.     public String mAppid = "222222";  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.acy_testqq);  
  21.         initView();  
  22.     }  
  23.   
  24.     public void initView() {  
  25.         mUserInfo = (TextView) findViewById(R.id.user_nickname);  
  26.         mUserLogo = (ImageView) findViewById(R.id.user_logo);  
  27.         mNewLoginButton = (Button) findViewById(R.id.new_login_btn);  
  28.         mNewLoginButton.setOnClickListener(this);  
  29.         backInfo = (TextView) findViewById(R.id.user_callback);  
  30.         // Tencent类是SDK的主要实现类,通过此访问腾讯开放的OpenAPI。  
  31.         mQQAuth = QQAuth.createInstance(mAppid, this.getApplicationContext());  
  32.         // 实例化  
  33.         mTencent = Tencent.createInstance(mAppid, this);  
  34.     }  
  35.   
  36.     Handler mHandler = new Handler() {  
  37.   
  38.         @Override  
  39.         public void handleMessage(Message msg) {  
  40.             if (msg.what == 0) {  
  41.                 mUserInfo.setVisibility(android.view.View.VISIBLE);  
  42.                 mUserInfo.setText(msg.getData().getString("nickname"));  
  43.             } else if (msg.what == 1) {  
  44.                 Bitmap bitmap = (Bitmap) msg.obj;  
  45.                 mUserLogo.setImageBitmap(bitmap);  
  46.                 mUserLogo.setVisibility(android.view.View.VISIBLE);  
  47.             }  
  48.         }  
  49.     };  
  50.   
  51.     private void updateUserInfo() {  
  52.         if (mQQAuth != null && mQQAuth.isSessionValid()) {  
  53.             IUiListener listener = new IUiListener() {  
  54.                 @Override  
  55.                 public void onError(UiError e) {  
  56.                     // TODO Auto-generated method stub  
  57.                 }  
  58.   
  59.                 @Override  
  60.                 public void onComplete(final Object response) {  
  61.                     JSONObject json = (JSONObject) response;  
  62.                     // 昵称  
  63.                     Message msg = new Message();  
  64.                     String nickname = null;  
  65.                     try {  
  66.                         nickname = ((JSONObject) response)  
  67.                                 .getString("nickname");  
  68.                     } catch (JSONException e) {  
  69.                         // TODO Auto-generated catch block  
  70.                         e.printStackTrace();  
  71.                     }  
  72.                     msg.getData().putString("nickname", nickname);  
  73.                     msg.what = 0;  
  74.                     mHandler.sendMessage(msg);  
  75.                     // 头像  
  76.                     String path;  
  77.                     try {  
  78.                         path = json.getString("figureurl_qq_2");  
  79.                         MyImgThread imgThread = new MyImgThread(path);  
  80.                         Thread thread = new Thread(imgThread);  
  81.                         thread.start();  
  82.                     } catch (JSONException e1) {  
  83.                         // TODO Auto-generated catch block  
  84.                         e1.printStackTrace();  
  85.                     }  
  86.                 }  
  87.   
  88.                 @Override  
  89.                 public void onCancel() {  
  90.                     // TODO Auto-generated method stub  
  91.   
  92.                 }  
  93.             };  
  94.             // MainActivity.mTencent.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO,  
  95.             // null,  
  96.             // Constants.HTTP_GET, requestListener, null);  
  97.             mInfo = new UserInfo(this, mQQAuth.getQQToken());  
  98.             mInfo.getUserInfo(listener);  
  99.   
  100.         } else {  
  101.             // mUserInfo.setText("");  
  102.             // mUserInfo.setVisibility(android.view.View.GONE);  
  103.             // mUserLogo.setVisibility(android.view.View.GONE);  
  104.         }  
  105.     }  
  106.   
  107.     /**  
  108.      * 开启线程 获取头像  
  109.      */  
  110.     class MyImgThread implements Runnable {  
  111.         private String imgPath;  
  112.         private Bitmap bitmap;  
  113.   
  114.         public MyImgThread(String imgpath) {  
  115.             this.imgPath = imgpath;  
  116.         }  
  117.   
  118.         @Override  
  119.         public void run() {  
  120.             // TODO Auto-generated method stub  
  121.             bitmap = getImgBitmap(imgPath);  
  122.             Message msg = new Message();  
  123.             msg.obj = bitmap;  
  124.             msg.what = 1;  
  125.             mHandler.sendMessage(msg);  
  126.         }  
  127.     }  
  128.   
  129.     /**  
  130.      * 根据头像的url 获取bitmap  
  131.      */  
  132.     public Bitmap getImgBitmap(String imageUri) {  
  133.         // 显示网络上的图片  
  134.         Bitmap bitmap = null;  
  135.         HttpURLConnection conn = null;  
  136.         InputStream is = null;  
  137.         try {  
  138.             URL myFileUrl = new URL(imageUri);  
  139.             conn = (HttpURLConnection) myFileUrl.openConnection();  
  140.             conn.setDoInput(true);  
  141.             conn.connect();  
  142.   
  143.             is = conn.getInputStream();  
  144.             bitmap = BitmapFactory.decodeStream(is);  
  145.             is.close();  
  146.         } catch (IOException e) {  
  147.             e.printStackTrace();  
  148.             return null;  
  149.         } finally {  
  150.             try {  
  151.                 conn.disconnect();  
  152.                 is.close();  
  153.                 is.reset();  
  154.             } catch (IOException e) {  
  155.                 // TODO Auto-generated catch block  
  156.                 e.printStackTrace();  
  157.             }  
  158.         }  
  159.         return bitmap;  
  160.     }  
  161.   
  162.     public void onClickLogin() {  
  163.         // 登录  
  164.         if (!mQQAuth.isSessionValid()) {  
  165.             // 实例化回调接口  
  166.             IUiListener listener = new BaseUiListener() {  
  167.                 @Override  
  168.                 protected void doComplete(JSONObject values) {  
  169.                     updateUserInfo();  
  170.                     // updateLoginButton();  
  171.                     if (mQQAuth != null) {  
  172.                         mNewLoginButton.setTextColor(Color.BLUE);  
  173.                         mNewLoginButton.setText("登录");  
  174.                     }  
  175.                 }  
  176.             };  
  177.             // "all": 所有权限,listener: 回调的实例  
  178.             // mQQAuth.login(this, "all", listener);  
  179.   
  180.             // 这版本登录是使用的这种方式,后面的几个参数是啥意思 我也没查到  
  181.             mTencent.loginWithOEM(this, "all", listener, "10000144",  
  182.                     "10000144", "xxxx");  
  183.         } else {  
  184.             // 注销登录  
  185.             mQQAuth.logout(this);  
  186.             updateUserInfo();  
  187.   
  188.             // updateLoginButton();  
  189.             mNewLoginButton.setTextColor(Color.RED);  
  190.             mNewLoginButton.setText("退出帐号");  
  191.         }  
  192.     }  
  193.   
  194.     /**  
  195.      * 调用SDK封装好的借口,需要传入回调的实例 会返回服务器的消息  
  196.      */  
  197.     private class BaseUiListener implements IUiListener {  
  198.         /**  
  199.          * 成功  
  200.          */  
  201.         @Override  
  202.         public void onComplete(Object response) {  
  203.             backInfo.setText(response.toString());  
  204.             doComplete((JSONObject) response);  
  205.         }  
  206.   
  207.         /**  
  208.          * 处理返回的消息 比如把json转换为对象什么的  
  209.          *   
  210.          * @param values  
  211.          */  
  212.         protected void doComplete(JSONObject values) {  
  213.   
  214.         }  
  215.   
  216.         @Override  
  217.         public void onError(UiError e) {  
  218.             Toast.makeText(TestQQ.this, e.toString(), 1000).show();  
  219.         }  
  220.   
  221.         @Override  
  222.         public void onCancel() {  
  223.             Toast.makeText(TestQQ.this, "cancel", 1000).show();  
  224.         }  
  225.     }  
  226.   
  227.     @Override  
  228.     public void onClick(View v) {  
  229.         // TODO Auto-generated method stub  
  230.         // 当点击登录按钮  
  231.         if (v == mNewLoginButton) {  
  232.             onClickLogin();  
  233.         }  
  234.     }  
  235.   
  236. }  

测试:

        1.运行的开始界面:

       2.当你的手机没用安装qq的时候,会跳转到网页qq注册界面:

       3.如果手机上有qq客户端:

       4.获取成功:


注意:

       1.因为我使用的是腾讯给的测试接口id,如果你也是使用的测试接口的话,那么记得把应用的名字改为: “open_sample”。

       2.在进行登录的时候,可以进行判断是否适合sso登录。

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. // 是否支持sso登录  
  2.             if (mTencent.isSupportSSOLogin(this)) {  
  3.                 onClickLogin();  
  4.             }  
当支持的时候,就返回真,否则返回假。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现第三方qq登录,可以使用QQ互联提供的开放平台接口。具体的步骤如下: 1. 注册成为QQ互联开发者,并创建应用。在创建应用时,需要填写应用的基本信息,并获得AppID和AppKey。 2. 在Spring Boot后端项目中,使用Spring Security实现OAuth2认证。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-client</artifactId> <version>5.3.4.RELEASE</version> </dependency> ``` 3. 在前端Vue项目中,使用Vue CLI创建项目,并安装vue-cli-plugin-qrcode实现生成二维码。在Terminal中运行以下命令: ``` vue create qq-login-demo cd qq-login-demo vue add qrcode ``` 4. 在Spring Boot后端项目中,实现OAuth2的配置。在application.yml文件中添加以下配置: ```yaml spring: security: oauth2: client: registration: qq: clientId: <your app id> clientSecret: <your app key> redirectUriTemplate: "{baseUrl}/login/oauth2/code/{registrationId}" authorizationUri: https://graph.qq.com/oauth2.0/authorize tokenUri: https://graph.qq.com/oauth2.0/token userInfoUri: https://graph.qq.com/user/get_user_info scope: - get_user_info provider: qq: authorizationUri: https://graph.qq.com/oauth2.0/authorize tokenUri: https://graph.qq.com/oauth2.0/token userInfoUri: https://graph.qq.com/user/get_user_info?oauth_consumer_key={clientId}&openid={oauthId} userNameAttribute: nickname ``` 5. 在前端Vue项目中,实现二维码生成。在App.vue文件中添加以下代码: ```vue <template> <div id="app"> <div v-if="!isLogin"> <qrcode :value="qrCodeUrl"></qrcode> </div> <div v-else> <p>{{ userInfo.nickname }}</p> <img :src="userInfo.figureurl_qq_1" alt="头像"> </div> </div> </template> <script> import QRCode from 'qrcode' export default { name: 'App', data() { return { isLogin: false, qrCodeUrl: '' } }, mounted() { this.generateQRCode() }, methods: { async generateQRCode() { const response = await this.$http.get('/qq-login/qr-code') if (response.status === 200) { this.qrCodeUrl = response.data this.isLogin = false } }, async checkLoginStatus() { const response = await this.$http.get('/qq-login/check-login-status') if (response.status === 200) { this.userInfo = response.data this.isLogin = true } } } } </script> ``` 6. 在Spring Boot后端项目中,实现二维码生成和登录状态检查。在QqLoginController.java文件中添加以下代码: ```java @RestController @RequestMapping("/qq-login") public class QqLoginController { private final OAuth2AuthorizedClientService authorizedClientService; private final RestTemplate restTemplate; @Autowired public QqLoginController(OAuth2AuthorizedClientService authorizedClientService, RestTemplate restTemplate) { this.authorizedClientService = authorizedClientService; this.restTemplate = restTemplate; } @GetMapping("/qr-code") public String generateQRCode() { String qrCodeUrl = "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=<your app id>&redirect_uri=http://localhost:8080/login&state=<random state>"; try { qrCodeUrl = QRCode.from(qrCodeUrl).to(ImageType.PNG).withSize(250, 250).stream().collect(Collectors.toBase64String); } catch (WriterException | IOException e) { e.printStackTrace(); } return "data:image/png;base64," + qrCodeUrl; } @GetMapping("/check-login-status") public Map<String, Object> checkLoginStatus() { OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); String accessToken = authorizedClient.getAccessToken().getTokenValue(); String openId = restTemplate.getForObject("https://graph.qq.com/oauth2.0/me?access_token=" + accessToken, String.class); openId = StringUtils.substringBetween(openId, "\"openid\":\"", "\"}"); Map<String, Object> userInfo = restTemplate.getForObject("https://graph.qq.com/user/get_user_info?access_token=" + accessToken + "&oauth_consumer_key=<your app id>&openid=" + openId, Map.class); return userInfo; } } ``` 7. 在前端Vue项目中,实现登录状态检查。在App.vue文件中添加以下代码: ```vue <script> export default { name: 'App', data() { return { isLogin: false, qrCodeUrl: '' } }, mounted() { this.generateQRCode() this.checkLoginStatus() setInterval(() => { this.checkLoginStatus() }, 3000) }, methods: { async checkLoginStatus() { const response = await this.$http.get('/qq-login/check-login-status') if (response.status === 200) { this.userInfo = response.data this.isLogin = true } } } } </script> ``` 至此,我们就成功地实现了Spring Boot+Vue代码实现第三方QQ登录的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值