微信授权

在Application中注册WXAPI

    private void registerWx() {
        IWXAPI wxAPI = WXAPIFactory.createWXAPI(this, null);
        wxAPI.registerApp(Constants.WX_APP_ID);
    }

在Activity中获取WXAPI

wxAPI = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);

向微信发送授权请求

SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "fm_withdraw_bind";
wxAPI.sendReq(req);

在应用包名的直接目录下,新建包wxapi,并创建如下Acitvity

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wx_result);

        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时,会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    @Override
    public void onResp(BaseResp baseResp) {
        LogUtils.d(TAG, "errCode = " + baseResp.errCode);
        //授权获取code
        if (baseResp instanceof SendAuth.Resp) {
            SendAuth.Resp authResp = (SendAuth.Resp) baseResp;
            String result;
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    WechatAuthEvent authEvent = WechatAuthEvent.obtain(true, authResp.code);
                    EventBus.getDefault().post(authEvent);
                    close();
                    return;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = "您取消了授权";
                    close();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = "授权被拒绝";
                    close();
                    break;
                default:
                    result = "授权失败";
                    close();
                    break;
            }
        }else{
            close();
        }
    }

    private void close(){
        finish();
        overridePendingTransition(0,0);
    }
}

然后在自己的Activity中获取(使用EventBus接收)

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wechatAuth(WechatAuthEvent authEvent) {
        if (authEvent.isSuccess()) {
            // TODO 上报给应用服务器
        }
    }

 

微信授权

上一篇:微信红包随机算法


下一篇:类似tabBar的切换页面效果(微信小程序)