手把手教你Android集成第三方微信登录

最近公司要求集成第三方的微信登录功能,以前没做过,现在做完梳理下思路。

  1、首先要在微信开放平台注册你的APP。获取APPidAPPSecret

  2、然后要集成微信的sdk jar


3、创建一个和你包名一致的包例如:你的包名是com.yanglei.cn,那么你所需创建的包名就是com.yanglei.cn.wxapi,在这个包名下,我们要创建一个WXEntryActivity.java的类继承Activity并且实现IWXAPIEventHandler,并重写protected void onNewIntent(Intent intent)public void onReq(BaseReq arg0)public void onResp(BaseResp resp)方法。WXEntryActivity.java文件可以见最后附录。注意:一定是包名目录下新建,不要在其他目录新建,否则WXEntryActivity.java里的public void onResp(BaseResp resp)方法不会被调用

3、注册到微信

WXEntryActivity.javaoncreate方法中

private IWXAPI api;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

api = WXAPIFactory.createWXAPI(this, 你申请的appid);

        api.handleIntent(getIntent(), this);

       

}

 

4、发送微信登录的请求

app中点击某一个view,发送微信登录的请求如下:

/**

 * 微信登录

 * @param v

 */

public void weixinLogin(View v){

//toast("dianj");

loginWithWeixin();

}

/**

 * 微信登录的方法

 */

private void loginWithWeixin() {

    if (api == null) {

     api = WXAPIFactory.createWXAPI(this, WeiXinConstant.WEIXIN_APP_ID, false);

    }

 

    if (!api.isWXAppInstalled()) {

      //提醒用户没有按照微信

      return;

    }

    

 //注册微信登录

    api.registerApp(WeiXinConstant.WEIXIN_APP_ID);

  //激活微信登录吊起微信授权

    SendAuth.Req req = new SendAuth.Req();

    req.scope = "snsapi_userinfo";

req.state = "wechat_sdk_demo";

api.sendReq(req);

  }

请求成功后,可拉起微信的授权登录页面,如下。用户点击“确认登录”后,SDK通过SendAuth的Resp返回数据给调用方(即app),此时WXEntryActivity中的public void onResp(BaseResp resp)方法被调用(微信、朋友圈分享成功后,此方法同样会被调用),微信登录的返回值说明如下。这里app可以做相关的处理,见WXEntryActivity.java文件中的处理,取code为下一步获取access_token和openid等信息做准备。此处获取code的方法:

//微信登录接口实现的 方法 注意:该方法一定要在程序的包名下才会被调用否则拿不到返回值code

@Override

public void onResp(BaseResp resp) {

switch (resp.errCode) {

case BaseResp.ErrCode.ERR_OK:

code = ((SendAuth.Resp) resp).code;

//这个是获取微信token等信息的方法

getWeiXinInfo(code);

Toast.makeText(this, "授权成功,登录请稍等...", Toast.LENGTH_SHORT)

.show();

handler.sendEmptyMessageDelayed(0, 1000);

handler.sendEmptyMessageDelayed(1, 2000);

break;

case BaseResp.ErrCode.ERR_USER_CANCEL:

Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT)

.show();

break;

case BaseResp.ErrCode.ERR_AUTH_DENIED:

Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT)

.show();

break;

default:

break;

}

}

当微信被调起后如图:


6、通过code获取access_token等信息的方法:

private void getWeiXinInfo(String code) {

String getWeiXinOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"

+ "appid="

//你的appid

+ WeiXinConstant.WEIXIN_APP_ID

+ "&secret="

//你的APPSecret

+ WeiXinConstant.WEIXIN_APP_SECRET

+ "&code="

+ code

+ "&grant_type=authorization_code";

applyHttpRequest(getWeiXinOpenIdUrl, null, new ComeBackRequestData() {

@Override

public void onSuccess(String message) {

Log.i("weixin", message);

System.out.println("微信放回的信息:"+message);

processWeiXinData(message);

}

@Override

public void onStart(String msg) {

}

@Override

public void onLoading(long total, long current, boolean isUploading) {

}

@Override

public void onFailure(int errorCode, String msg) {

}

});

}

返回值:

{"access_token":"RwvWW1dasg9w80ZQzQ-e5u66AcgVdzni75tu1wxRxyHzleUMqaoOMiR6jKrF3orlcYrrx_0LvaFimTr1yoWDYU0qHqDOOK-0G15SJ9kXQsQ","expires_in":7200,"refresh_token":"I_vWVI_5xcrXNn-UZRTHFg-bl70dAtxwCG6tqa1hm6jPELGzBijjggRX8-GNKlUz-p7GdLHapvd9m8GFtqhW4nHHVVGD8RGnMyoHvZHxuSk","openid":"oVznnv784FX6VEPeKoGxKrwpyNhY","scope":"snsapi_userinfo","unionid":"oAiDjsnbYuREtqGJdwjDY3CvbqiA"}

 

 

7、获取用户的信息:

private void getUserInfo() {

String openid = sp.getString("openid", null);

String token = sp.getString("token", null);

String getWeiXinTokenIdUrl="https://api.weixin.qq.com/sns/userinfo?"+"access_token="+token+"&openid="+openid;

applyHttpRequest(getWeiXinTokenIdUrl, null, new ComeBackRequestData() {

@Override

public void onSuccess(String message) {

Log.i("weixin", message);

System.out.println("用户信息:"+message);

processWeiXinUserInfo(message);

}

@Override

public void onStart(String msg) {

}

@Override

public void onLoading(long total, long current, boolean isUploading) {

}

@Override

public void onFailure(int errorCode, String msg) {

}

});

}

返回值:

用户信息:{"openid":"oVznnv784FX6VEPeKoGxKrwpyNhY","nickname":"じ☆vewo冋歸洎己灬","sex":1,"language":"zh_CN","city":"Changchun","province":"Jilin","country":"CN","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/SapRqL7kibvXMeFJAzIr6HQlV3KLwlgsctdFnFXPGt0sKSR7bYKiagU2QoQkpcpbIqFwqQ4kjoDalN1ibVFd6SWtEV2OGUZVdUia\/0","privilege":[],"unionid":"oAiDjsnbYuREtqGJdwjDY3CvbqiA"}

 

8、获得access_token、openid后,app就可以根据自己的规则与互自己的server进行交互

 

WXEntryActivity.java:

package com.ledon.ledonmobiledevice.wxapi;

 

public class WXEntryActivity extends NetworkRequestActivity implements IWXAPIEventHandler {

//第三方标识

private String thirdIdentify="1";

private IWXAPI api;

private Map<String, String> weixinMap;

private WeiXinBean weiXinBean;

private SharedPreferences sp;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

//微信登录所需

api = WXAPIFactory.createWXAPI(this, WeiXinConstant.WEIXIN_APP_ID);

        api.handleIntent(getIntent(), this);

        sp = getSharedPreferences("Weixin", MODE_PRIVATE);

      

}

 

/**

 * 微信登录

 * @param v

 */

public void weixinLogin(View v){

//toast("dianj");

loginWithWeixin();

}

/**

 * 微信登录的方法

 */

private void loginWithWeixin() {

    if (api == null) {

     api = WXAPIFactory.createWXAPI(this, WeiXinConstant.WEIXIN_APP_ID, false);

    }

 

    if (!api.isWXAppInstalled()) {

      //提醒用户没有按照微信

      return;

    }

    

 //注册微信登录

    api.registerApp(WeiXinConstant.WEIXIN_APP_ID);

  //激活微信登录吊起微信授权

    SendAuth.Req req = new SendAuth.Req();

    req.scope = "snsapi_userinfo";

req.state = "wechat_sdk_demo";

api.sendReq(req);

  }

 

//微信登录接口实现的 方法

@Override

public void onReq(BaseReq req) {

switch (req.getType()) {

 

case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:

break;

case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:

break;

default:

break;

}

}

//微信登录接口实现的 方法

@Override

protected void onNewIntent(Intent intent) {

super.onNewIntent(intent);

setIntent(intent);

        api.handleIntent(intent, this);

}

private Handler handler=new Handler(){

public void handleMessage(android.os.Message msg) {

switch (msg.what) {

case 0:

getUserInfo();

break;

case 1:

login();

break;

 

default:

break;

}

};

};

private String code;

//微信登录接口实现的 方法 注意:该方法一定要在程序的包名下才会被调用否则拿不到返回值code

@Override

public void onResp(BaseResp resp) {

switch (resp.errCode) {

case BaseResp.ErrCode.ERR_OK:

code = ((SendAuth.Resp) resp).code;

getWeiXinInfo(code);

//new WeiXinLogin(this).getWeiXinInfo(code);

//getToken();

//handler.sendEmptyMessage(0);

Toast.makeText(this, "授权成功,登录请稍等...", Toast.LENGTH_SHORT)

.show();

handler.sendEmptyMessageDelayed(0, 1000);

handler.sendEmptyMessageDelayed(1, 2000);

break;

case BaseResp.ErrCode.ERR_USER_CANCEL:

Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT)

.show();

break;

case BaseResp.ErrCode.ERR_AUTH_DENIED:

Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT)

.show();

break;

default:

break;

}

}

private void getUserInfo() {

String openid = sp.getString("openid", null);

String token = sp.getString("token", null);

String getWeiXinTokenIdUrl="https://api.weixin.qq.com/sns/userinfo?"+"access_token="+token+"&openid="+openid;

applyHttpRequest(getWeiXinTokenIdUrl, null, new ComeBackRequestData() {

@Override

public void onSuccess(String message) {

Log.i("weixin", message);

System.out.println("用户信息:"+message);

processWeiXinUserInfo(message);

}

@Override

public void onStart(String msg) {

}

@Override

public void onLoading(long total, long current, boolean isUploading) {

}

@Override

public void onFailure(int errorCode, String msg) {

}

});

}

 

private void getWeiXinInfo(String code) {

String getWeiXinOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"

+ "appid="

+ WeiXinConstant.WEIXIN_APP_ID

+ "&secret="

+ WeiXinConstant.WEIXIN_APP_SECRET

+ "&code="

+ code

+ "&grant_type=authorization_code";

applyHttpRequest(getWeiXinOpenIdUrl, null, new ComeBackRequestData() {

@Override

public void onSuccess(String message) {

Log.i("weixin", message);

System.out.println("微信放回的信息:"+message);

processWeiXinData(message);

}

 

@Override

public void onStart(String msg) {

}

@Override

public void onLoading(long total, long current, boolean isUploading) {

}

@Override

public void onFailure(int errorCode, String msg) {

}

});

}

private void login(){

}

}

 


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值