您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“android微信授權(quán)怎么獲取用戶個(gè)人信息”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“android微信授權(quán)怎么獲取用戶個(gè)人信息”吧!
微信官方文檔API:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
1.申請(qǐng)你的 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注冊(cè)到微信
IWXAPI msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true); if (msgApi.isWXAppInstalled()) { // 將應(yīng)用的appId注冊(cè)到微信 msgApi.registerApp(Constant.AppID); //建議動(dòng)態(tài)監(jiān)聽微信啟動(dòng)廣播進(jìn)行注冊(cè)到微信 registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 將該app注冊(cè)到微信 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, "請(qǐng)安裝微信客戶端后進(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ā)送請(qǐng)求到第三方應(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; } } //注冊(cè)廣播 @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)登錄,請(qǐng)求 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注冊(cè)到微信 msgApi.registerApp(Constant.AppID); //建議動(dòng)態(tài)監(jiān)聽微信啟動(dòng)廣播進(jìn)行注冊(cè)到微信 registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 將該app注冊(cè)到微信 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/oauth3/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/oauth3/refresh_token?").params(map).build().execute( new StringCallback() { @Override public void onError(Call call, Exception e, int id) { Log.i("微信刷新TokenError", e.getMessage()); // 重新請(qǐng)求授權(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); } } } }
到此,相信大家對(duì)“android微信授權(quán)怎么獲取用戶個(gè)人信息”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。