WXEntryActivity.java 7.83 KB
package com.cnlive.strike.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cnlive.libs.base.application.AppConfig;
import com.cnlive.libs.base.util.AlertUtil;
import com.cnlive.share.arouter.ARouterUtil;
import com.cnlive.share.data.ShareIntegralTypeInfo;
import com.cnlive.share.data.WeChatInfo;
import com.cnlive.share.observable.WechatLoginObservable;
import com.cnlive.share.observable.WechatShareObservable;
import com.cnlive.share.util.DateTimeUtil;
import com.cnlive.share.util.OkHttpUtils;
import com.cnlive.strike.user.auth.UserService;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import com.cnlive.share.BuildConfig;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 作者: 吴奎庆
 * <p>
 * 时间: 2018/8/23
 * <p>
 * 简介:
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, BuildConfig.WECHAT_SHARE,false);
        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) {
    }


    private SendAuth.Resp resp;

    @Override
    public void onResp(BaseResp baseResp) {

        //微信登录为getType为1,分享为0
        if (baseResp.getType() == 1) {
            //登录回调
            resp = (SendAuth.Resp) baseResp;
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    String code = String.valueOf(resp.code);
                    //获取用户信息
                    getAccessToken(code);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                    AlertUtil.showDeftToast(this, "用户拒绝授权");
                    this.finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                    AlertUtil.showDeftToast(this, "用户取消登录");
                    this.finish();
                    break;
                default:
                    this.finish();
                    break;
            }
        } else {
            String result = "";
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    result = "分享成功";
                    WechatShareObservable.getInstance().update(1);
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = "分享取消";
                    WechatShareObservable.getInstance().update(2);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = "分享失败";
                    WechatShareObservable.getInstance().update(3);
                    break;
                default:
                    result = "分享失败";
                    break;
            }

            AlertUtil.showDeftToast(this, result);
            this.finish();
            processShareType(baseResp);
        }


    }

    private void getAccessToken(String code) {
        String getTokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=%s&secret=%s&code=%s&grant_type=authorization_code", AppConfig.getWechatAppid(),
                BuildConfig.WECHAT_KEY, code);
        OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId + "";
                OkHttpUtils.ResultCallback<WeChatInfo> resultCallback = new OkHttpUtils.ResultCallback<WeChatInfo>() {
                    @Override
                    public void onSuccess(WeChatInfo response) {
                        response.setErrCode(resp.errCode);
                        if (response != null) WechatLoginObservable.getInstance().update(response);
                        finish();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                };
                OkHttpUtils.get(getUserInfo, resultCallback);
            }

            @Override
            public void onFailure(Exception e) {
                Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
        };
        OkHttpUtils.get(getTokenUrl, resultCallback);

    }


    /**
     * 更具不同的分享类型处理不同的 分享逻辑
     *
     * @param baseResp
     */
    private void processShareType(BaseResp baseResp) {
        String shareType = baseResp.transaction;
        if (TextUtils.isEmpty(shareType)) return;
        try {
            Gson gson = new Gson();
            ShareIntegralTypeInfo integralTypeInfo = gson.fromJson(shareType, ShareIntegralTypeInfo.class);

            if ("witnessVideo".equals(integralTypeInfo.getShareType())) {
                SharedPreferences preferences = this.getSharedPreferences("sharevideo", MODE_PRIVATE);
                boolean status = preferences.getBoolean(UserService.getUid(this), false);
                String newTime = DateTimeUtil.getCurrentTime();
                String oldtime = preferences.getString(UserService.getUid(this) + "time", "2019-04-10");
                boolean sameDay = DateTimeUtil.isSameDay(newTime, oldtime);
                if (!status) {
                    ARouterUtil.addIntegrationPic(this, "share_video", integralTypeInfo.getContentId(), "sharevideo");
                }
                if (status && !sameDay) {
                    ARouterUtil.addIntegrationPic(this, "share_video", integralTypeInfo.getContentId(), "sharevideo");
                }

            } else if (integralTypeInfo.getShareType() != null) {
                SharedPreferences preferences = this.getSharedPreferences("sharearticle", MODE_PRIVATE);
                boolean status = preferences.getBoolean(UserService.getUid(this), false);
                String newTime = DateTimeUtil.getCurrentTime();
                String oldtime = preferences.getString(UserService.getUid(this) + "time", "2019-04-10");
                boolean sameDay = DateTimeUtil.isSameDay(newTime, oldtime);
                if (!status) {
                    ARouterUtil.addIntegrationPic(this, "share_article", integralTypeInfo.getContentId(), "sharearticle");
                }
                if (status && !sameDay) {
                    ARouterUtil.addIntegrationPic(this, "share_article", integralTypeInfo.getContentId(), "sharearticle");
                }
            }

        } catch (Exception e) {
            return;
        }
    }
}