Android (微信扫码登录) 获取微信二维码+扫码登录

话不多说  直接上菜!

一.因为是微信扫码登录,所有要在微信开放平台  微信开放平台 (qq.com) 进行注册----- 如下 

1.资源中心 里面也有详细的官方讲解,里面也有demo  可以下载

 

 

 

 

 2.在 管理中心      创建应用 填写一系列的信息  

 

 

 3. 提交审核,大概需要三到五天的时间审核完成;

 4. 审核完成微信开放平台会生成一个appid,和sercet 这两个是唯一的id 需要妥善保管;

 5. 按照微信开放平台给的文档,下载相应的sdk以及签名工具,在此强调 必须是用签名打包的正式版的apk才可以调起微信的客户端进行授权登录,必须保证应用的签名(用签名工具可以获取)和开放平台上填写的信息一致。   签名工具获取----》首页-----》资源中心---》资源下载

 

 

 

 

 

 

6.将 自己的app 安装到手机

7.将 签名生成工具 下载安装到 (6.上一步中的)手机,打开并输入 (6.上一步app)的包名,并点击 get 按钮,生成签名,填写到  第2步 中.

 

 

 

 

 二.代码部分

1、依赖:在app  build.gradle 中添加

  implementation ‘com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+’

 implementation 'com.google.code.gson:gson:2.8.5'

 

2.我用的是HTTP 请求  当然也可以用OKHTTP 会更简单一些

  新建 HttpsUtils 类库,写里面的 submitGetData 方法如下:

/**
* 使用GET方法读取http中的数据
*
* @param strUrlPath url地址
* @return 请求的响应数据
*/
public static String submitGetData(String strUrlPath, @NonNull Map<String, String> requestPropertys) throws Exception {
// 创建URL对象
URL url = new URL(strUrlPath);
// 打开连接 获取连接对象
URLConnection connection = url.openConnection();
connection.setConnectTimeout(6000);

if (requestPropertys != null) {
//设置 安卓端flag
for (Map.Entry<String, String> entry : requestPropertys.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}

// 从连接对象中获取网络连接中的输入字节流对象
InputStream inputStream = connection.getInputStream();
// 将输入字节流包装成输入字符流对象,并进行字符编码
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
// 创建一个输入缓冲区对象,将字符流对象传入
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

// 定义一个字符串变量,用来接收输入缓冲区中的每一行字符串数据
String line;
// 创建一个可变字符串对象,用来装载缓冲区对象的数据,使用字符串追加的方式,将响应的所有数据都保存在该对象中
StringBuilder stringBuilder = new StringBuilder();
// 使用循环逐行读取输入缓冲区的数据,每次循环读入一行字符串数据赋值给line字符串变量,直到读取的行为空时标识内容读取结束循环
while ((line = bufferedReader.readLine()) != null) {
// 将从输入缓冲区读取到的数据追加到可变字符对象中
stringBuilder.append(line);
}
// 依次关闭打开的输入流
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
// 将可变字符串转换成String对象返回
return stringBuilder.toString();
}
3.把申请出来的appID,secret 放在新建的Constant类中

 

 



4.我们回到 MainActivity中
//定义变量
private ImageView IvWeChat;  //显示 二维码的图片控件
IDiffDevOAuth oauth;
String noncestr;
String timeStamp;
String sha;
Toast mToast;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

oauth = DiffDevOAuthFactory.getDiffDevOAuth(); //添加
IvWeChat = (ImageView) findViewById(R.id.iv_wxm);

ConnectWechat();
}
//回调
   OAuthListener mOAuthListener = new OAuthListener() {
@Override
public void onAuthGotQrcode(String s, byte[] bytes) {
Log.e(TAG, "onAuthGotQrcode: ");
IvWeChat.setImageBitmap(null);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, new BitmapFactory.Options());
IvWeChat.setImageBitmap(bitmap);
}

@Override
public void onQrcodeScanned() {

}

@Override
public void onAuthFinish(OAuthErrCode oAuthErrCode, String s) {
Log.e(TAG, "onAuthFinish: ");
if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_OK) {
new Thread(new Runnable() {
@Override
public void run() {
try {

String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_SECRET + "&code=" + s + "&grant_type=authorization_code";
Log.e(TAG, "onAuthFinish: url: " + url);
String res = HttpsUtils.submitGetData(url, null);
Log.e(TAG, "服务器返回: " + res);
JSONObject jsonObject = new JSONObject(res);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");

url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
res = HttpsUtils.submitGetData(url, null);
Log.e(TAG, "服务器返回: " + res);
jsonObject = new JSONObject(res);
String unionid = jsonObject.getString("unionid");
openid = jsonObject.getString("openid");
String nickName = jsonObject.getString("nickname");
int sex = jsonObject.getInt("sex");
String headimgurl = jsonObject.getString("headimgurl");
String language = jsonObject.getString("language");
String city = jsonObject.getString("city");
String province = jsonObject.getString("province");
String country = jsonObject.getString("country");
JSONArray privilege = jsonObject.getJSONArray("privilege");
Log.e(TAG, "unionid: " + unionid);
Log.e(TAG, "openid: " + openid);
Log.e(TAG, "nickName: " + nickName);
Log.e(TAG, "sex: " + sex);
Log.e(TAG, "headimgurl: " + headimgurl);
Log.e(TAG, "language: " + language);
Log.e(TAG, "city: " + city);
Log.e(TAG, "province: " + province);
Log.e(TAG, "country: " + country);
Log.e(TAG, "privilege: " + privilege);

runOnUiThread(new Runnable() {
@Override
public void run() {

//扫码成功 然后跳转
startActivity(new Intent(此页面.this, 想要跳转的页面.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

}
});

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

}
}).start();
} else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_Timeout) {
showTip("二维码已过期,请点击刷新"); //这个是提示 也可以用 吐司
//Toast.makeText()


} else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_Cancel) {
showTip("没有授权返回在刷新一下二维码");

} else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_NetworkErr) {
showTip("网络错误");

}
}
};




    /**
* 获取access_token
*
* @param
*/

private void ConnectWechat() {
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_SECRET;
Log.e(TAG, "url_1: " + url);
String res = HttpsUtils.submitGetData(url, null);
Log.e(TAG, "服务器返回: " + res);

//获取access_token
String access_token = new JSONObject(res).getString("access_token");
url = "https:api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=2";
Log.e(TAG, "url_2: " + url);

res = HttpsUtils.submitGetData(url, null);

Log.e(TAG, "服务器返回: " + res);
String ticket = new JSONObject(res).getString("ticket");

StringBuilder str = new StringBuilder();// 定义变长字符串
// 随机生成数字,并添加到字符串
for (int i = 0; i < 8; i++) {
str.append(new Random().nextInt(10));
}
noncestr = str.toString();
timeStamp = Long.toString(System.currentTimeMillis()).substring(0, 10);
String string1 = String.format("appid=%s&noncestr=%s&sdk_ticket=%s&timestamp=%s", Constant.WECHAT_APPID, noncestr, ticket, timeStamp);
sha = EncryptUtils.getSHA(string1);
Log.e(TAG, "二维码验证方式" + sha);
oauth.auth(Constant.WECHAT_APPID, "snsapi_userinfo", noncestr, timeStamp, sha, mOAuthListener);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

//重写onDestroy
@Override
protected void onDestroy() {
super.onDestroy();
//二维码登录
oauth.removeAllListeners();
oauth.stopAuth();
}

//OK,到这里呢,就结束了!
//兄弟们,加油,干就完了,奥里给!没有什么能阻挡我们前进的步伐。





posted on 2022-06-27 21:33  Bytezero!  阅读(2334)  评论(1编辑  收藏  举报