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) {
//設置 Android端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 = "//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 = "//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 = "//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,到這裡呢,就結束了!
//兄弟們,加油,干就完了,奧里給!沒有什麼能阻擋我們前進的步伐。