微信登錄的實作與qq登錄類似,不過微信登錄比較麻煩,需要拿到開發者資質認證,花300塊錢,然后應用的話還得有官網之類的,就是比較繁瑣的前期準備作業,如果在公司里,這些應該都不是事,會有相關人提前準備好,在這里我們已經拿到了開發者認證,并且申請到了微信登錄的授權,

現在直接介紹mob來實作微信登錄的代碼,并獲取微信的相關資料,比較簡單,
一、布局界面
布局界面只需要一個button來觸發授權就可以
<Button
android:id="@+id/wxlogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微信登錄" />
二、MainActivity.java
public class MainActivity extends Activity {
private Button wxlogin;
private Platform wx;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
wxlogin = (Button) login_view.findViewById(R.id.wxlogin);
wxlogin.setOnClickListener(new wxloginListener());
}
private class wxloginListener implements OnClickListener {
@Override
public void onClick(View arg0) {
wx = ShareSDK.getPlatform(Wechat.NAME);
System.out.println("微信是否已經授權1:"+wx.isAuthValid());
if(wx.isAuthValid()){
wx.removeAccount(true);
}
System.out.println("微信是否已經授權2:"+wx.isAuthValid());
wx.SSOSetting(false); // 設定false表示使用SSO授權方式
wx.authorize();
wx.showUser(null);
wx.setPlatformActionListener(new PlatformActionListener() {
@Override
public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
System.out.println("wx登錄測驗hashMap"+hashMap);
System.out.println("wx登錄測驗hashMap"+hashMap.toString());
String unionid = (String) hashMap.get("unionid");
System.out.println("wx登錄測驗unionid"+unionid);
System.out.println("wx登錄測驗"+platform.getDb().toString());
String thirdLoginId = platform.getDb().getUserId();
System.out.println("wx登錄測驗thirdLoginId:"+thirdLoginId);
String userName = platform.getDb().getUserName();
System.out.println("wx登錄測驗userName:"+ userName);
String image = platform.getDb().getUserIcon();
System.out.println("wx登錄測驗image:"+image);
String sex = qq.getDb().getUserGender();
System.out.println("wx登錄測驗sex:"+sex);
System.out.println("wx登錄測驗:"+"成功了");
}
@Override
public void onError(Platform platform, int i, Throwable throwable) {
}
@Override
public void onCancel(Platform platform, int i) {
}
});
wx.removeAccount(true);
System.out.println("微信是否已經授權3:"+wx.isAuthValid());
}
}
}

這是官方提供的介面,
- plat. authorize():要功能不要資料 單獨授權(只獲取授權資訊,不獲取用戶資訊)
- plat. showUser(null):要資料無需功能à授權并獲取資訊(除了授權資訊,其他用戶資訊可以在oncomplete中的hashmap中獲取)

這樣就拿到的微信的授權,并且獲得資料,然后將資料向資料庫中存盤,就可以做微信登錄了,
總體流程來說還是比較簡單,直接呼叫介面就行,就是前期的審核準備作業比較麻煩,
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/292535.html
標籤:其他
