微信官方文档API:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
1.申请你的 AppID
只有审核通过的应用才能进行开发。
2.下载 SDK 及 API 文档
Android Studio 环境下:
在 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()) {// 将应用的appId注册到微信msgApi.registerApp(Constant.AppID);//建议动态监听微信启动广播进行注册到微信registerReceiver(new BroadcastReceiver() {@Overridepublic 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"; //获取用户个人信息则填写 snsapi_userinforeq.state =  "mvwl-"; //可根据项目填写msgApi.sendReq(req);} else {Toast.makeText(LoginActivity.this, "请安装微信客户端后进行此操作").show();return;}

4.创建WXEntryActivity,在AndroidMainifest.xml中添加WXEntryActivity

public class WXEntryActivity extends WXCallbackActivity  implements IWXAPIEventHandler {public static final String WXLOGIN_ACTION = "com.mvw.test.wxlogin";private IWXAPI iwxapi;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);iwxapi = WXAPIFactory.createWXAPI(this, "自己项目APPID", true);try {Intent intent = getIntent();iwxapi.handleIntent(intent, this);} catch (Exception e) {e.printStackTrace();}}@Overrideprotected void onNewIntent(Intent intent) {super.onNewIntent(intent);setIntent(intent);iwxapi.handleIntent(intent, this);}// 微信发送请求到第三方应用时,会回调到该方法@Overridepublic void onReq(BaseReq baseReq) {switch (baseReq.getType()) {case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:break;case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:break;default:break;}}@Overridepublic void onResp(BaseResp baseResp) {Intent intent = new Intent(WXLOGIN_ACTION);//登录回调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;//用户拒绝授权case BaseResp.ErrCode.ERR_AUTH_DENIED:intent.putExtra("error_code", -4);break;//用户取消授权case BaseResp.ErrCode.ERR_USER_CANCEL:intent.putExtra("error_code", -2);break;}sendBroadcast(intent);  //使用了广播finish();}
}
<activityandroid:configChanges="keyboardHidden|orientation|screenSize"android:exported="true"android:name=".wxapi.WXEntryActivity"android:theme="@android:style/Theme.Translucent.NoTitleBar" />

5.接收微信返回参数code,根据code获取access_token,获取用户个人信息
下面是完整的使用列子。

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_tokenprivate String WEIXIN_OPENID_KEY = "wx_openid_key"; //微信openidprivate String WEIXIN_REFRESH_TOKEN_KEY = "wx_refresh_token_key";//微信refresh_tokenprivate String WEIXIN_UNIONID = "wx_unionid_key";//微信unionidprivate Activity activity;private IWXAPI msgApi;private WXLoginReceiver wxLoginReceiver;private  boolean flag=false;@Overrideprotected 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);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.iv_weChat:registerWeChat();break;}}//注册广播@Overrideprotected void onResume() {super.onResume();flag = true;if (wxLoginReceiver == null) {IntentFilter wxIntent = new IntentFilter(WXEntryActivity.WXLOGIN_ACTION);wxLoginReceiver = new WXLoginReceiver();registerReceiver(wxLoginReceiver, wxIntent);}}/*** 微信登录成功接收广播* ShareUtilService 封装的SharedPreferences存储方法*/class WXLoginReceiver extends BroadcastReceiver {@Overridepublic 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_tokengetAccessToken(code);}}break;case -4: //用户拒绝授权case -2:  //用户取消授权Log.i("微信", "onReceive: " + error_code);break;}}}}/*** 微信授权登录,请求 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()) {// 将应用的appId注册到微信msgApi.registerApp(Constant.AppID);//建议动态监听微信启动广播进行注册到微信registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// 将该app注册到微信msgApi.registerApp("自己项目APPID");}}, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));final Req req = new Req();req.scope = "snsapi_userinfo";req.state =  "mvwl-";//根据自己项目需要定义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", "自己项目APPID");map.put("secret", "自己项目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() {@Overridepublic void onError(Call call, Exception e, int id) {Log.i("微信获取Err", e.getMessage());}@Overridepublic 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 接口调用凭证* @param openid 授权用户唯一标识*/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() {@Overridepublic void onError(Call call, Exception e, int id) {Log.i("微信用户信息Err", e.getMessage());}@Overridepublic 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 授权用户唯一标识*/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() {@Overridepublic void onError(Call call, Exception e, int id) {Log.i("微信token过期Err", e.getMessage());}@Overridepublic 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来刷新accesstokenrefreshAccessToken();}} catch (JSONException e) {e.printStackTrace();}}});}/*** 刷新获取新的access_token*/private void refreshAccessToken() {// 从本地获取以存储的refresh_tokenString refreshToken = ShareUtilService.getString(WEIXIN_REFRESH_TOKEN_KEY, "");if (TextUtils.isEmpty(refreshToken)) {return;}Map<String, String> map = new HashMap<>();map.put("appid", "自己项目的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() {@Overridepublic void onError(Call call, Exception e, int id) {Log.i("微信刷新TokenError", e.getMessage());// 重新请求授权registerWeChat();}@Overridepublic 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();}}});}@Overrideprotected void onDestroy() {super.onDestroy();if(flag){flag=false;if (wxLoginReceiver != null) {unregisterReceiver(wxLoginReceiver);}}}
}

android 微信授权获取用户个人信息相关推荐

  1. 微信授权获取openID等信息,这里简化记录一下

    微信授权获取openID等信息 微信测试平台连接:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 授权操作必须用外网(推荐 ...

  2. 微信公众号开发之微信网页授权获取用户个人信息

    说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 一丶概述 微信网页授权 如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑 ...

  3. 微信h5获取用户地址信息

    微信h5页面获取用户地址信息(vue+Java)(清风竹语) 前言: 与之前获取用户信息相同,这次获取用户地址信息也是在用户进入该页面之后,通过取得用户经纬度,在调用高德地图的api获得位置信息. 流 ...

  4. 微信授权获取用户的openid和支付宝授权获取用户的userid

    为什么80%的码农都做不了架构师?>>>    当一请求一个链接或者是扫描二维码时,会请求后台方法,当然对于微信和支付宝来说,大多数时候是扫 码 一.首先说微信: 1.首先会判断请求 ...

  5. 微信授权获取用户openid前端实现

    近来,倒霉的后台跟我说让我拿个openid做微信支付使用,寻思很简单,开始干活. 首先引导用户打开如下链接,只需要将appid修改为自己的就可以,redirect_url写你的重定向url https ...

  6. Java实现微信授权 获取用户OpenID(简单易实现)

    接上篇,我们从微信开发文档获取openid后,感觉这种方式有点麻烦,今天给大家推荐更好的一种方法,GitHub - Wechat-Group/WxJava: 微信开发 Java SDK ,支持包括微信 ...

  7. 微信公众号网页授权获取用户信息的流程

    官网文档 网页授权流程分为四步: 引导用户进入授权页面同意授权,获取code 通过 code 换取网页授权access_token(与基础支持中的access_token不同)(我的需求只需要到第二部 ...

  8. 微信OAuth授权获取用户OpenId-JAVA(个人经验)

    个人微信小程序 可扫码体验 本文更新有可能先在开源中国.地址为:https://my.oschina.net/xshuai/blog/293458 https://open.weixin.qq.com ...

  9. 微信OAuth授权获取用户OpenId-JAVA

    开源中国http://my.oschina.net/xshuai/blog/293458也是本作者 https://open.weixin.qq.com/ 这个是授权登陆自己网站的和我的这个是有区别的 ...

最新文章

  1. 羡慕嫉妒!看了腾讯月收入 8 万 的支出账单不恨了 | 每日趣闻
  2. 炼丹知识点:模型评估里的陷阱
  3. 云话题 | 5G消息是什么?
  4. 全排列函数、组合函数
  5. [react] React的render中可以写{if else}这样的判断吗?
  6. Nginx常见错误码解决方案
  7. 30个最常用css选择器解析(经典)
  8. module 'bit' not found:No LuaRocks module found for bit
  9. 简述:bs和cs的区别
  10. JUCE学习笔记06-音频输出基础(正弦波)
  11. c4d快速启动语言对话框脚本错误,如何解决“当前页面脚本发生错误”的问题
  12. 蓝牙耳机排名前十:618性价比超高的真无线蓝牙耳机推荐!
  13. sqlserver2000安装时提示挂起并重启
  14. iOS发展史:从iPhone OS 1.0到iOS10 终于支持骚扰拦截了
  15. 英文事件抽取论文整理
  16. 大数据能否带来风控革命
  17. PPT乱码如何解决?
  18. 隐忍成大事:春秋五霸楚庄王必成雄主之谜
  19. Linux安装配置ssh 基于unbantu22.04.1 LTS版本
  20. 5000字长文:电商运营如何做好数据分析?

热门文章

  1. Spring5基础知识
  2. html图片在表格平铺,CSS----层级、背景图片,表格
  3. Java后端开发工程师
  4. linux服务器被植入挖矿病毒后初步解决方案
  5. 微信扫付款后,付错款,不是好友也能联系到收款方
  6. php工作日,计算工作日的天数
  7. ubuntu右上角没有网的问题解决
  8. 如何将.keystore 文件转成.key文件
  9. 基于Fortran的结构力学位移法编程求解
  10. OpenGL配置glut64位和glut32位,英伟达 安全 下载地址 免费