微信登录与分享和支付

public class WeChatUtil {
    private static WeChatUtil instance;
    private static final String TAG = WeChatUtil.class.getName();
    private String WXAPP_ID = "";
    private String WXAPP_SECRET = "";
    public static final int IMAGE_SIZE = 32768;//微信分享图片大小限制


    private IWXAPI api;
    private static Application application;
    private WeiXinToken mWeiXinToken;
    private WeiXinInfo mWeiXinInfo;

    public static WeChatUtil getInstance() {
        if (instance == null) {
            instance = new WeChatUtil();
            application = MyApplication.getmApplication();
        }
        return instance;
    }

    public void initWechatLogin() {
        api = WXAPIFactory.createWXAPI(application, WXAPP_ID, true);
        api.registerApp(WXAPP_ID);
        application.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                api.registerApp(WXAPP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }

    /**
     * 微信登陆(三个步骤)
     * 1.微信授权登陆
     * 2.根据授权登陆code 获取该用户token
     * 3.根据token获取用户资料
     */
    public void login() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = String.valueOf(System.currentTimeMillis());
        api.sendReq(req);
    }

    public void getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + WXAPP_ID + "&secret=" + WXAPP_SECRET +
                "&code=" + code + "&grant_type=authorization_code";
        OkGo.<WeiXinToken>post(url)
                .tag("WeiXinToken")
                .retryCount(2)
                .execute(new JsonCallback<WeiXinToken>() {
                    @Override
                    public void onSuccess(Response<WeiXinToken> response) {
                        WeiXinToken weiXinToken = response.body();
                        if (weiXinToken.getErrcode() == 0) {
                            getWeiXinUserInfo(weiXinToken);
                            setmWeiXinToken(weiXinToken);
                        } else {
                            ToastUtil.showToast(weiXinToken.getErrmsg());
                        }
                    }

                    @Override
                    public void onError(Response<WeiXinToken> response) {
                        super.onError(response);
                        ToastUtil.showToast(response.message());
                    }
                });
    }

    public void getWeiXinUserInfo(WeiXinToken weiXinToken) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                weiXinToken.getAccess_token() + "&openid=" + weiXinToken.getOpenid();
        OkGo.<WeiXinInfo>post(url)
                .tag("WeiXinInfo")
                .retryCount(2)
                .execute(new JsonCallback<WeiXinInfo>() {
                    @Override
                    public void onSuccess(Response<WeiXinInfo> response) {
                        WeiXinInfo weiXinInfo = response.body();
                        setmWeiXinInfo(weiXinInfo);
                        XLog.json(weiXinInfo.toString());
                        ToastUtil.showToast(weiXinInfo.toString());
                    }
                });
    }

    /**
     * 微信分享
     *
     * @param friendsCircle 是否分享到朋友圈
     */
    public void share(boolean friendsCircle) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "www.yunjichina.com.cn";//分享url
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "云迹科技";
        msg.description = "云迹科技,机器人行业探索者,专注于商用服务机器人研发,产品涉及酒店机器人、迎宾机器人、讲解机器人、送餐机器人、机器人底盘等。";
        msg.thumbData = getThumbData();//封面图片byte数组

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = friendsCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    /**
     * 获取分享封面byte数组 我们这边取的是软件启动icon
     *
     * @return
     */
    private byte[] getThumbData() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeResource(application.getResources(), R.drawable.ic_launcher, options);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
        int quality = 100;
        while (output.toByteArray().length > IMAGE_SIZE && quality != 10) {
            output.reset(); // 清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, output);// 这里压缩options%,把压缩后的数据存放到baos中
            quality -= 10;
        }
        bitmap.recycle();
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发起支付
     *
     * @param weiXinPay
     */
    public void pay(WeiXinPay weiXinPay) {
        PayReq req = new PayReq();
        req.appId = WXAPP_ID;//appid
        req.nonceStr = weiXinPay.getNoncestr();//随机字符串,不长于32位。推荐随机数生成算法
        req.packageValue = weiXinPay.getPackage_value();//暂填写固定值Sign=WXPay
        req.sign = weiXinPay.getSign();//签名
        req.partnerId = weiXinPay.getPartnerid();//微信支付分配的商户号
        req.prepayId = weiXinPay.getPrepayid();//微信返回的支付交易会话ID
        req.timeStamp = weiXinPay.getTimestamp();//时间戳

        api.registerApp(WXAPP_ID);
        api.sendReq(req);
    }

    public WeiXinToken getmWeiXinToken() {
        return mWeiXinToken;
    }

    public void setmWeiXinToken(WeiXinToken mWeiXinToken) {
        this.mWeiXinToken = mWeiXinToken;
    }

    public WeiXinInfo getmWeiXinInfo() {
        return mWeiXinInfo;
    }

    public void setmWeiXinInfo(WeiXinInfo mWeiXinInfo) {
        this.mWeiXinInfo = mWeiXinInfo;
    }

    public IWXAPI getApi() {
        return api;
    }
}
public class WXEntryActivity extends BaseMvpLanActivity<WXEntryPresent> implements IWXAPIEventHandler {
    private static final String TAG = WXEntryActivity.class.getName();

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        WeChatUtil.getInstance().getApi().handleIntent(getIntent(), this);
        XLog.i(TAG, "WXEntryActivity onNewIntent");
    }

    @Override
    public void onReq(BaseReq baseReq) {
        XLog.i(TAG, "WXEntryActivity onReq:" + baseReq);
    }

    @Override
    public void onResp(BaseResp resp) {
        XLog.i(TAG, "WXEntryActivity onResp:" + resp);
        if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {//分享
            XLog.i(TAG, "微信分享操作.....");
            WeiXin weiXin = new WeiXin(2, resp.errCode, "");
            EventBus.getDefault().post(weiXin);
        } else if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {//登陆
            XLog.i(TAG, "微信登录操作.....");
            SendAuth.Resp authResp = (SendAuth.Resp) resp;
            WeiXin weiXin = new WeiXin(1, resp.errCode, authResp.code);
            EventBus.getDefault().post(weiXin);
        }
        finish();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        WeChatUtil.getInstance().getApi().handleIntent(getIntent(), this);
    }

    @Override
    public WXEntryPresent newP() {
        return new WXEntryPresent();
    }
}
public class WXPayEntryActivity extends BaseMvpLanActivity<WXPayEntryPresent> implements IWXAPIEventHandler {
    @Override
    public void initData(Bundle savedInstanceState) {
        WeChatUtil.getInstance().getApi().handleIntent(getIntent(), this);
    }

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


    @Override
    public WXPayEntryPresent newP() {
        return new WXPayEntryPresent();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        XLog.i("whh", "微信支付回调 返回错误码:" + resp.errCode + " 错误名称:" + resp.errStr);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {//微信支付
            WeiXin weiXin = new WeiXin(3, resp.errCode, "");
            EventBus.getDefault().post(weiXin);
        }
        finish();
    }
}
@Subscribe
    public void onEventMainThread(WeiXin weiXin) {
        XLog.i("whh", "收到eventbus请求 type:" + weiXin.getType());
        if (weiXin.getType() == 1) {//登录
            WeChatUtil.getInstance().getAccessToken(weiXin.getCode());
        } else if (weiXin.getType() == 2) {//分享
            switch (weiXin.getErrCode()) {
                case BaseResp.ErrCode.ERR_OK:
                    XLog.i("whh", "微信分享成功.....");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL://分享取消
                    XLog.i("whh", "微信分享取消.....");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED://分享被拒绝
                    XLog.i("whh", "微信分享被拒绝.....");
                    break;
            }
        } else if (weiXin.getType() == 3) {//微信支付
            if (weiXin.getErrCode() == BaseResp.ErrCode.ERR_OK) {//成功
                XLog.i("whh", "微信支付成功.....");
            }
        }
    }