微信官方文档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注册到微信
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22IWXAPI msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true); if (msgApi.isWXAppInstalled()) { // 将应用的appId注册到微信 msgApi.registerApp(Constant.AppID); //建议动态监听微信启动广播进行注册到微信 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"; //获取用户个人信息则填写 snsapi_userinfo req.state = "mvwl-"; //可根据项目填写 msgApi.sendReq(req); } else { Toast.makeText(LoginActivity.this, "请安装微信客户端后进行此操作").show(); return; }
4.创建WXEntryActivity,在AndroidMainifest.xml中添加WXEntryActivity
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59public 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, "自己项目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); } // 微信发送请求到第三方应用时,会回调到该方法 @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); //登录回调 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(); } }
复制代码
1
2
3
4
5<activity android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:name=".wxapi.WXEntryActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
5.接收微信返回参数code,根据code获取access_token,获取用户个人信息
下面是完整的使用列子。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322package 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存储方法 */ 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: //用户拒绝授权 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() { @Override public 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() { @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 接口调用凭证 * @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() { @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 授权用户唯一标识 */ 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() { // 从本地获取以存储的refresh_token String 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() { @Override public void onError(Call call, Exception e, int id) { Log.i("微信刷新TokenError", e.getMessage()); // 重新请求授权 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); } } } }
到此这篇关于android微信授权获取用户个人信息代码的文章就介绍到这了,更多相关android微信授权内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!
最后
以上就是俊秀纸鹤最近收集整理的关于android微信授权获取用户个人信息代码的全部内容,更多相关android微信授权获取用户个人信息代码内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复