准备工作:可写一个Demo
1、我们首先需要去微信平台申请的app应用,绑定一个app,并去申请功能的使用权限。
微信开放平台:https://open.weixin.qq.com/cgi-bin/index?t=home/index&lang=zh_CN(资源中心··网站应用)
2、在微信平台申请的app,先打包(非debug包),在打包后的app应用软件里下载一个app签名工具,在app签名工具里面输入app manifest里的包名,包名是package里的,一定要是这个包名,别把包名弄混了,最后生成一个签名,放在微信开放平台的信息输入框里面。
untitled1.png
3、然后就是调用微信的回调类: WXEntryActivity 而且这个类名必须是这个,而这个类名必须在.wxapi包名下,不然微信无法掉起,并在AndroidManifest.xml配置(包名要用自己的包名)。
<activity
android:name="com.example.weixindemo.wxapi.WXEntryActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<!-- <data android:scheme="wxXXX0" /> -->
<!-- <data android:scheme="wxXXX1" /> -->
<data android:scheme="wxXXX2" />
</intent-filter>
</activity>
untitled.png
4、去自己申请的app里面拿到appid和secret这两个key。(可利用其先在网页中先验证获取的code值是不是正常的)
// 微信APPID,若改动,AndroidManifest中也应修改
//正式环境
public static final String WX_APPID = "wxXXX0";
//测试环境
// public static final String WX_APPID = "wxXXX1";
//微信支付APPID
public static final String WX_APPID_PAY = "wxXXX2";
5、代码:WXEntryActivity.java
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, Consts.WX_APPID);
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) {
LogUtil.e("rd96", "WxEntryActivity onReq::::");
}
// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
@Override
public void onResp(BaseResp baseResp) {
LogUtil.e("rd96", "WxEntryActivity 授权回调 code:::" + baseResp.errCode);
EventBus.getDefault().post(baseResp);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
api.detach();
}
}
去请求授权登录页:
// 授权登陆,前提是设备已安装微信应用并已登录,未登录的会引导你先登录
private static void registerToWx(final BaseActivity context) {
try {
// 通过WXAPIFactory工厂获取IWXApI的实例
IWXAPI wxApi = WXAPIFactory.createWXAPI(context, Consts.WX_APPID, true);
// 将应用的appid注册到微信
wxApi.registerApp(Consts.WX_APPID);
if (null != wxApi && wxApi.isWXAppInstalled()) {
// send oauth request,Final
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo";
wxApi.sendReq(req);
} else {
EventDispatcher.getInstance().postMainRunnable(new Runnable() {
@Override
public void run() {
Toast.makeText(context.getApplicationContext(), R.string.weChat_uninstall, Toast.LENGTH_SHORT).show();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity中:(获取到--微信授权临时票据code,发送给后台,后台去获取access_token,再去取得具体信息,再发送过来,这边再做处理,同步数据)
@Subscribe(threadMode = ThreadMode.MAIN)
public void registerToWXResp(BaseResp baseResp){
if (baseResp.getType() == 1) { // 1是登录 2是分享
if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
// "授权成功"
SendAuth.Resp re = ((SendAuth.Resp) baseResp);
code = re.code;
getWeChatInfo(); // 向后台发送请求,并更新数据
} else if (baseResp.errCode == BaseResp.ErrCode.ERR_COMM) {
// 错误;可能的原因:签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
Toast.makeText(getContext(), "抱歉,授权失败", Toast.LENGTH_SHORT).show();
} else if (baseResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
Toast.makeText(getContext(), "您已取消授权", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "授权被拒绝", Toast.LENGTH_SHORT).show();
}
}
}
网络访问工具类--Rxjava(XLUserRpc.WxAuthAndGetBasicUserInfoReq 和 WxAuthAndGetBasicUserInfoResp 后台提供),NettyEndpoint--Socket io 封装(网络情况相关处理)
// 获取微信信息,并更新数据
private void getWeChatInfo() {
showLoadingProgressDialog(false,false, getString(R.string.weChat_sync));
Observable.create(new ObservableOnSubscribe<Response>() {
@Override
public void subscribe(final ObservableEmitter<Response> e) throws Exception {
final XLUserRpc.WxAuthAndGetBasicUserInfoReq.Builder req = XLUserRpc.WxAuthAndGetBasicUserInfoReq.newBuilder();
req.setCode(code);//微信用户的code
NettyEndpoint.getInstance().sendRequest(req.build(), new NetCallback() {
@Override
public void callback(Response response) {
e.onNext(response);
}
});
}
}).subscribeOn(Schedulers.io())
.compose(this.<Response>bindUntilEvent(FragmentEvent.DESTROY))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ConsumerObserver<Response>(new Consumer<Response>(){
@Override
public void accept(Response response) throws Exception {
hideLoadingProgressDialog();
if(response.errorCode == Consts.NETWORK_SUCCESS) {
if (null != response.resp) {
XLUserRpc.WxAuthAndGetBasicUserInfoResp resp = (XLUserRpc.WxAuthAndGetBasicUserInfoResp)response.resp;
updateUserData(resp);
}
}else {
if (ChatUtils.handleTimeoutException(getActivity(), response.errorCode)) {
// timeout
} else {
XLUserRpc.WxAuthAndGetBasicUserInfoResp resp = (XLUserRpc.WxAuthAndGetBasicUserInfoResp) response.resp;
if (null == resp || TextUtils.isEmpty(resp.getErrorMessage())) {
Toast.makeText(getContext(), getString(R.string.NetworkBusy), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), getString(R.string.weChat_sync_fail), Toast.LENGTH_SHORT).show();
}
}
}
}
}));
}
通过code获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
参考:
https://blog.csdn.net/k571039838k/article/details/82591819
https://www.cnblogs.com/kenshinobiy/p/8640006.html
网友评论