欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

android微信授權(quán)獲取用戶個(gè)人信息代碼

 更新時(shí)間:2021年12月30日 15:11:23   作者:前端小白123  
大家好,本篇文章主要講的是android微信授權(quán)獲取用戶個(gè)人信息代碼,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽

微信官方文檔API:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html

1.申請你的 AppID

只有審核通過的應(yīng)用才能進(jìn)行開發(fā)。

2.下載 SDK 及 API 文檔

Android Studio 環(huán)境下:

在 build.gradle 文件中,添加如下依賴即可:
dependencies {
implementation ‘com.tencent.mm.opensdk:wechat-sdk-android:6.8.0'
}

3.將APP注冊到微信

    IWXAPI msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true);

    if (msgApi.isWXAppInstalled()) {
      // 將應(yīng)用的appId注冊到微信
      msgApi.registerApp(Constant.AppID);
      //建議動(dòng)態(tài)監(jiān)聽微信啟動(dòng)廣播進(jìn)行注冊到微信
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          // 將該app注冊到微信
          msgApi.registerApp(Constant.AppID);
        }
      }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
      final Req req = new Req();
      req.scope = "snsapi_userinfo"; //獲取用戶個(gè)人信息則填寫 snsapi_userinfo
      req.state =  "mvwl-"; //可根據(jù)項(xiàng)目填寫
      msgApi.sendReq(req);
    } else {
      Toast.makeText(LoginActivity.this, "請安裝微信客戶端后進(jìn)行此操作").show();
      return;

    }

4.創(chuàng)建WXEntryActivity,在AndroidMainifest.xml中添加WXEntryActivity

public class WXEntryActivity extends WXCallbackActivity  implements IWXAPIEventHandler {
  public static final String WXLOGIN_ACTION = "com.mvw.test.wxlogin";
  private IWXAPI iwxapi;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    iwxapi = WXAPIFactory.createWXAPI(this, "自己項(xiàng)目APPID", true);
    try {
      Intent intent = getIntent();
      iwxapi.handleIntent(intent, this);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    iwxapi.handleIntent(intent, this);
  }
  // 微信發(fā)送請求到第三方應(yīng)用時(shí),會(huì)回調(diào)到該方法
  @Override
  public void onReq(BaseReq baseReq) {
    switch (baseReq.getType()) {
      case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
        break;
      case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
        break;
      default:
        break;
    }
  }

  @Override
  public void onResp(BaseResp baseResp) {
    Intent intent = new Intent(WXLOGIN_ACTION);
    //登錄回調(diào)
    Log.i("微信", "onResp: "+ baseResp.errCode);
    switch (baseResp.errCode){
      case BaseResp.ErrCode.ERR_OK:
        String code = ((SendAuth.Resp) baseResp).code;
        intent.putExtra("Wx_Login", code);
        intent.putExtra("error_code", 0);
        break;
      //用戶拒絕授權(quán)
      case BaseResp.ErrCode.ERR_AUTH_DENIED:
        intent.putExtra("error_code", -4);
        break;
      //用戶取消授權(quán)
      case BaseResp.ErrCode.ERR_USER_CANCEL:
        intent.putExtra("error_code", -2);
        break;
    }
    sendBroadcast(intent);  //使用了廣播
    finish();
  }
}

<activity
      android:configChanges="keyboardHidden|orientation|screenSize"
      android:exported="true"
      android:name=".wxapi.WXEntryActivity"
      android:theme="@android:style/Theme.Translucent.NoTitleBar" />

5.接收微信返回參數(shù)code,根據(jù)code獲取access_token,獲取用戶個(gè)人信息
下面是完整的使用列子。

package com.mvw.test.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;test
import com.google.gson.GsonBuilder;
import com.mvw.test.R;
import com.mvw.test.wxapi.WXEntryActivity;
import com.test.netlibrary.OkHttpUtils;
import com.test.netlibrary.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth.Req;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.PlatformConfig;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.MediaType;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 登錄
 */
public class LoginActivity extends Activity implements View.OnClickListener {
private String WEIXIN_ACCESS_TOKEN_KEY = "wx_access_token_key"; //微信access_token
  private String WEIXIN_OPENID_KEY = "wx_openid_key"; //微信openid
  private String WEIXIN_REFRESH_TOKEN_KEY = "wx_refresh_token_key";//微信refresh_token
  private String WEIXIN_UNIONID = "wx_unionid_key";//微信unionid
  private Activity activity;
  private IWXAPI msgApi;
  private WXLoginReceiver wxLoginReceiver;
  private  boolean flag=false;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    activity = this;
    initView();
  }
  private void initView() {
    ImageView iv_weChat = (ImageView) findViewById(R.id.iv_weChat);
    iv_weChat.setOnClickListener(this);
  }
  
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.iv_weChat:
           registerWeChat();
        break;
    }
  }


//注冊廣播
  @Override
  protected void onResume() {
    super.onResume();
    flag = true;
    if (wxLoginReceiver == null) {
       IntentFilter wxIntent = new IntentFilter(WXEntryActivity.WXLOGIN_ACTION);
      wxLoginReceiver = new WXLoginReceiver();
       registerReceiver(wxLoginReceiver, wxIntent);
    }

  }

  /**
   * 微信登錄成功接收廣播
   * ShareUtilService 封裝的SharedPreferences存儲(chǔ)方法
   */
  class WXLoginReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      String code = intent.getStringExtra("Wx_Login");
      int error_code = intent.getIntExtra("error_code", -1);
      if (TextUtils.equals(intent.getAction(), WXEntryActivity.WXLOGIN_ACTION)) {
        switch (error_code) {
          case 0:
            if (!code.isEmpty()) {
              String accessToken = ShareUtilService.getString(WEIXIN_ACCESS_TOKEN_KEY, "");
              String openid = ShareUtilService.getString(WEIXIN_OPENID_KEY, "");
              if (!"".equals(accessToken)) {
                // 有access_token,判斷是否過期有效
                isExpireAccessToken(accessToken, openid);
              } else {
                // 沒有access_token
                getAccessToken(code);
              }
            }
            break;
          case -4: //用戶拒絕授權(quán)
          case -2:  //用戶取消授權(quán)
            Log.i("微信", "onReceive: " + error_code);
            break;
        }

      }
    }
  }

  /**
   * 微信授權(quán)登錄,請求 CODE
   */
  private void registerWeChat() {
    ShareUtilService.remove(WEIXIN_REFRESH_TOKEN_KEY);
    ShareUtilService.remove(WEIXIN_ACCESS_TOKEN_KEY);
    ShareUtilService.remove(WEIXIN_OPENID_KEY);
    ShareUtilService.remove(WEIXIN_UNIONID);
    msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true);
    Log.i("微信", "registerWeChat: " + msgApi.isWXAppInstalled());
    if (msgApi.isWXAppInstalled()) {
      // 將應(yīng)用的appId注冊到微信
      msgApi.registerApp(Constant.AppID);
      //建議動(dòng)態(tài)監(jiān)聽微信啟動(dòng)廣播進(jìn)行注冊到微信
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          // 將該app注冊到微信
          msgApi.registerApp("自己項(xiàng)目APPID");
        }
      }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

      final Req req = new Req();
      req.scope = "snsapi_userinfo";
      req.state =  "mvwl-";//根據(jù)自己項(xiàng)目需要定義
      msgApi.sendReq(req);

    } else {
      Toast.makeText(LoginActivity.this, R.string.pay_wx_client_install,
          Toast.LENGTH_SHORT).show();
      return;

    }

  }

  /**
   * 微信獲取accessToken
   * @param code 微信返回的code
   */
  private void getAccessToken(String code) {
    Map<String, String> map = new HashMap<>();
    map.put("appid", "自己項(xiàng)目APPID");
    map.put("secret", "自己項(xiàng)目APPSecret");
    map.put("code", code);
    map.put("grant_type", "authorization_code");
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/access_token?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信獲取Err", e.getMessage());
         
          }

          @Override
          public void onResponse(String response, int id) {
            String access = null;
            String openid = null;
            try {
                JSONObject jsonObject = new JSONObject(response);
                access = jsonObject.getString("access_token");
                openid = jsonObject.getString("openid");
                String refresh = jsonObject.getString("refresh_token");
                ShareUtilService.setString(WEIXIN_ACCESS_TOKEN_KEY, access);
                ShareUtilService.setString(WEIXIN_OPENID_KEY, openid);
                ShareUtilService.setString(WEIXIN_REFRESH_TOKEN_KEY, refresh);
                getWeChatUserInfo(access, openid);
            } catch (JSONException e) {
              e.printStackTrace();
            }

          }
        });
  }

  /**
   * 獲取用戶信息
   * @param accessToken 接口調(diào)用憑證
   * @param openid 授權(quán)用戶唯一標(biāo)識(shí)
   */
  private void getWeChatUserInfo(String accessToken, String openid) {
    Map<String, String> map = new HashMap<>();
    map.put("access_token", accessToken);
    map.put("openid", openid);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/userinfo?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信用戶信息Err", e.getMessage());
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
                ShareUtilService.setString("userInfo", response);
                String unionid = jsonObject.getString("unionid");
                ShareUtilService.setString(WEIXIN_UNIONID,unionid);

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  /**
   * 判斷accesstoken是過期
   *
   * @param accessToken token
   * @param openid 授權(quán)用戶唯一標(biāo)識(shí)
   */
  private void isExpireAccessToken(final String accessToken, final String openid) {
    Map<String, String> map = new HashMap<>();
    map.put("access_token", accessToken);
    map.put("openid", openid);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/auth?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信token過期Err", e.getMessage());
            
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
              int errCode = jsonObject.getInt("errcode");
              if (errCode == 0) {
                getWeChatUserInfo(accessToken, openid);
              } else {
                // 過期了,使用refresh_token來刷新accesstoken
                refreshAccessToken();
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }

          }
        });

  }

  /**
   * 刷新獲取新的access_token
   */

  private void refreshAccessToken() {
    // 從本地獲取以存儲(chǔ)的refresh_token
    String refreshToken = ShareUtilService.getString(WEIXIN_REFRESH_TOKEN_KEY, "");
    if (TextUtils.isEmpty(refreshToken)) {
      return;
    }
    Map<String, String> map = new HashMap<>();
    map.put("appid", "自己項(xiàng)目的APPID“);
    map.put("grant_type", "refresh_token");
    map.put("refresh_token", refreshToken);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/refresh_token?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信刷新TokenError", e.getMessage());
            // 重新請求授權(quán)
            registerWeChat();
          }
          @Override
          public void onResponse(String response, int id) {
            try {
               JSONObject jsonObject = new JSONObject(response);
                String access = jsonObject.getString("access_token");
                String openid = jsonObject.getString("openid");
                getWeChatUserInfo(access, openid);
        
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if(flag){
      flag=false;
      if (wxLoginReceiver != null) {
        unregisterReceiver(wxLoginReceiver);
      }
    }

  }
}

到此這篇關(guān)于android微信授權(quán)獲取用戶個(gè)人信息代碼的文章就介紹到這了,更多相關(guān)android微信授權(quán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android編程使用GestureDetector實(shí)現(xiàn)簡單手勢監(jiān)聽與處理的方法

    Android編程使用GestureDetector實(shí)現(xiàn)簡單手勢監(jiān)聽與處理的方法

    這篇文章主要介紹了Android編程使用GestureDetector實(shí)現(xiàn)簡單手勢監(jiān)聽與處理的方法,簡單講述了Android手勢監(jiān)聽的原理并結(jié)合實(shí)例形式分析了GestureDetector實(shí)現(xiàn)手勢監(jiān)聽與處理的相關(guān)操作技巧,需要的朋友可以參考下
    2017-09-09
  • 淺析Android代碼質(zhì)量管理

    淺析Android代碼質(zhì)量管理

    本篇文章給大家分享了Android代碼質(zhì)量管理的相關(guān)知識(shí)點(diǎn)以及重點(diǎn)分析,對(duì)此有興趣的朋友可以參考學(xué)習(xí)下。
    2018-05-05
  • 九宮圖比較常用的多控件布局(GridView)使用介紹

    九宮圖比較常用的多控件布局(GridView)使用介紹

    GridView跟ListView都是比較常用的多控件布局,而GridView更是實(shí)現(xiàn)九宮圖的首選,下面與大家分享下GridView用法,感興趣的朋友可以參考下哈
    2013-06-06
  • Android手機(jī)屏幕同步工具asm.jar

    Android手機(jī)屏幕同步工具asm.jar

    今天小編就為大家分享一篇關(guān)于Android手機(jī)屏幕同步工具asm.jar的文章,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • 揭秘雙十一手機(jī)淘寶圖標(biāo)如何被動(dòng)態(tài)更換

    揭秘雙十一手機(jī)淘寶圖標(biāo)如何被動(dòng)態(tài)更換

    這篇文章主要介紹了每到雙十一十二的時(shí)候Android手機(jī)動(dòng)態(tài)更換手機(jī)圖標(biāo)的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • 實(shí)例講解Android中的AutoCompleteTextView自動(dòng)補(bǔ)全組件

    實(shí)例講解Android中的AutoCompleteTextView自動(dòng)補(bǔ)全組件

    AutoCompleteTextView組件被用在輸入框中能實(shí)現(xiàn)輸入內(nèi)容自動(dòng)補(bǔ)全的功能,類似于大家平時(shí)用Google時(shí)的輸入聯(lián)想,這里我們來用實(shí)例講解Android中的AutoCompleteTextView自動(dòng)補(bǔ)全組件,特別是實(shí)現(xiàn)郵箱地址補(bǔ)全的例子,非常實(shí)用
    2016-05-05
  • Android Textview實(shí)現(xiàn)顏色漸變滾動(dòng)效果

    Android Textview實(shí)現(xiàn)顏色漸變滾動(dòng)效果

    這篇文章主要為大家詳細(xì)介紹了Android Textview實(shí)現(xiàn)顏色漸變滾動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Android編程之動(dòng)態(tài)壁紙實(shí)例分析

    Android編程之動(dòng)態(tài)壁紙實(shí)例分析

    這篇文章主要介紹了Android編程之動(dòng)態(tài)壁紙實(shí)現(xiàn)方法,以實(shí)例形式分析了Android動(dòng)態(tài)壁紙的原理與實(shí)現(xiàn)步驟,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-12-12
  • Android開發(fā)實(shí)現(xiàn)生成excel的方法詳解

    Android開發(fā)實(shí)現(xiàn)生成excel的方法詳解

    這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)生成excel的方法,結(jié)合實(shí)例形式詳細(xì)分析了Android生成Excel的具體步驟與存儲(chǔ)、導(dǎo)入、添加等相關(guān)操作技巧,需要的朋友可以參考下
    2017-10-10
  • Android模糊處理簡單實(shí)現(xiàn)毛玻璃效果

    Android模糊處理簡單實(shí)現(xiàn)毛玻璃效果

    這篇文章主要介紹了Android模糊處理簡單實(shí)現(xiàn)毛玻璃效果的相關(guān)資料,需要的朋友可以參考下
    2016-02-02

最新評(píng)論