天天看點

Android內建微信SDK掃碼登入功能

最近做一個android項目,需求是登入頁面加入微信二維碼掃碼登入入口(類似于PC端掃一掃登入

Android內建微信SDK掃碼登入功能

),使用者打開微信APP,掃描二維碼,點選登入即可。當時也看了官網的相關介紹,确實踩了不少坑,寫這個部落格記錄下。

一、準備工作

1、compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'

2、Activity實作OAuthListener接口

  • onAuthGotQrcode(String qrcodeImgPath, byte[] bytes)//auth之後傳回的二維碼,Bitmap bmp =                          BitmapFactory.decodeByteArray(bytes, 0, bytes.length)即可擷取二維碼圖檔。
  • onQrcodeScanned()//使用者掃描二維碼之後,回調該方法
  • onAuthFinish(OAuthErrCode errCode, String authCode)//使用者點選授權和異常資訊,回調該方法

3、IDiffDevOAuth 初始化:IDiffDevOAuth  oauth = DiffDevOAuthFactory.getDiffDevOAuth();

二、擷取access_token

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

三、擷取Ticket

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=2

四、生成掃碼登入的簽名

參與簽名的字段包括第三方appid,noncestr(随機字元串), 有效的sdk_ticket, timestamp(時間戳)

String string1 = String.format("appid=%s&noncestr=%s&sdk_ticket=%s&timestamp=%s", APPID, nonceStr, ticket, timeStamp);

ShaUtils.encode(string1);

五、生成二維碼

oauth.auth(APPID, //應用唯一辨別

                "snsapi_userinfo", //demo給的是snsapi_login,此處是坑

                nonceStr,

                timestamp,

                ShaUtils.encode(string1), //簽名,步驟四生成的簽名

                this); // 授權完成回調接口(OAuthListener)

六、擷取新的token及openid

onAuthFinish即使用者授權後,拿傳回的authcode調接口(https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code)擷取新的token及openid

七、擷取使用者資訊

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID