安卓微信登录,分享,支付

1.准备工作

  1. 在微信开放平台注册好账号,和获得WX_AppID。

  2. 添加依赖 : api ‘com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+’

  3. 在BaseApplication里注册微信登录

    wxapi = WXAPIFactory.createWXAPI(this, Configure.WX_AppID, false);
    wxapi.registerApp(Configure.WX_AppID);

  4. 在清单文件里添加

        
    
    
        
    

2.微信登录和分享的实现类

public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    private OkHttpClient okHttpClient;
    private boolean isShareMoney = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //如果没回调onResp,八成是这句没有写
        BaseApplication.getWxApi().handleIntent(getIntent(), this);
    }



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

    }
    /**
     * 接收从小程序跳转到app的数据,并进行处理
     *
     * @param showReq
     */
    private void goToShowMsg(ShowMessageFromWX.Req showReq) {

    }
    /**
     * 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
     * app发送消息给微信,处理返回消息的回调
     *
     * @param baseResp
     */
    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) {
                    ToastUtils.showToast("分享失败");
                } else {
                    ToastUtils.showToast("登录失败");
                }
                break;
            case BaseResp.ErrCode.ERR_OK:
                switch (baseResp.getType()) {
                    case RETURN_MSG_TYPE_LOGIN:
                        finish();
                        //拿到了微信返回的code,立马再去请求access_token
                        String code = ((SendAuth.Resp) baseResp).code;
                        //通过code获取用户个人信息(UnionID机制)
                        getWxUnionID(code);
                        break;
                    case RETURN_MSG_TYPE_SHARE:
                        String transaction = baseResp.transaction;
                        if (transaction != null && Configure.SHARE_MONEY1.equals(transaction)) {
                            ShareMoneyDialog.initInstance(this).show(getFragmentManager(), "WXEntryActivity");
                        }else if (transaction != null && Configure.SHARE_MONEY2.equals(transaction)) {
                            ShareMoneyDialog.initInstance(this).show(getFragmentManager(), "WXEntryActivity");
                        }else if (transaction != null && "miniProgram".equals(transaction)) {
                            ToastUtils.showToast("分享小程序成功");
                            finish();
                        } else {
                            ToastUtils.showToast("分享成功");
                            finish();
                        }
                        break;
                }
                break;
            default:
                finish();
                break;
        }
    }

    /**
     * 获取用户个人信息(UnionID机制)
     *
     * @param code
     */
    private void getWxUnionID(String code) {
        ToastUtils.showLoadDialog("连接微信中...");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Configure.WX_AppID + "&secret=" + Configure.WX_AppSecret + "&code=" + code + "&grant_type=authorization_code";
        okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.closeLoadDialog();
                ToastUtils.showToast(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ToastUtils.closeLoadDialog();
                String result = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String unionid = (String) jsonObject.get("unionid");
                    // TODO: 2018/5/15 需要调用检测unionid
                    WXLoginO(unionid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (result == null) {
                    return;
                }

            }
        });
    }

    /**
     * 运营商微信登录
     *
     * @param unionid
     */
    private void WXLoginO(final String unionid) {
        ToastUtils.showLoadDialog("微信登录...");
        ApiService.checkUnionId(unionid).subscribe(new CallBack() {

            @Override
            protected void errorBody(String code, String message, String result) {
                ToastUtils.closeLoadDialog();

                if ("2".equals(code)) {//跳转到注册
//                    ACache.getAsString(AcacheKey.UNIONID);
                    RouterUtils.openPage(RouterPath.REGISTER_PAGE, "unionid", unionid);
                    return;
                }
                if ("3".equals(code)) {
                    ToastUtils.showToast("您已经是师傅了,不能注册运营商");
                } else {
                    ToastUtils.showToast(message);
                }
            }

            @Override
            protected void requestBody(LoginEntity data, String message) {
                ToastUtils.closeLoadDialog();
                //存储厂商ID
                PreferencesUtils.putString(AcacheKey.MANUFACTUREID, data.getManufacturerId());
                PreferencesUtils.putString(AcacheKey.SESSIONID, data.getSessionId());
                PreferencesUtils.putString(AcacheKey.USERID, data.getUserId());
                PreferencesUtils.putString(AcacheKey.USER_VIP, data.getPayStatus());
                JPushInterface.setAlias(BaseApplication.getCurrentActivity(), data.getUserId(), new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set set) {

                    }
                });
                String easemobUserName = data.getEasemobUserName();
                String easemobPassWord = data.getEasemobPassWord();
                //环信登陆
                if (easemobUserName != null && easemobPassWord != null) {
//                    ToastUtils.showLoadDialog("信息初始化中...");
                    HXLoginUtils.hxLogin(easemobUserName, easemobPassWord);
                } else {
                    JPushInterface.resumePush(BaseApplication.getInstance());
                    RouterUtils.openPage(RouterPath.MAIN_OPERATOR);
                }

            }
        });
    }
}

3.微信支付的实现类

public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {
    @Override
    protected int createView() {
        return R.layout.activity_wxpay_entry;
    }
    @Override
    protected void initData() {
        //如果没回调onResp,八成是这句没有写
        BaseApplication.getWxApi().handleIntent(getIntent(), this);
    }
    @Override
    public void onReq(BaseReq baseReq) {
    }
    @Override
    public void onResp(BaseResp resp) {
        /**
         * 结果码参考:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_5
         */
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            int code = resp.errCode;
            switch (code) {
                case 0:
                    ToastUtils.showToast("支付成功");
                    PayResp myResp = (PayResp) resp;
                    String transaction = myResp.extData;
                    if (transaction != null && Configure.BUY_SUCCESS1.equals(transaction)) {//购买短信成功
                        EventbusUtils.sendEvent(new Event(EventC.UPDATE_BUY_MSG_INFO));
                    }
                    if (transaction != null && Configure.BUY_SUCCESS2.equals(transaction)) {//购买会员成功
                        EventbusUtils.sendEvent(new Event(EventC.UPDATE_BUY_VIP_INFO));
                        PreferencesUtils.putString(AcacheKey.USER_VIP, "3");
                    }
                    finish();
                    break;
                case -1:
                    finish();
                    // 支付失败 可能的原因:签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    ToastUtils.showToast("支付失败");
                    break;
                case -2:
                    finish();
                    ToastUtils.showToast("支付取消");
                    break;
            }
        }
    }
}

4.微信分享的工具类

public class ShareFriendsUtils {
    private static WXMediaMessage wxMediaMessage;

    /**
     * 把url分享到朋友圈
     *
     * @param mContext
     * @param url
     * @param title
     * @param imgUrl
     */
    public static void shareToFriends(Context mContext, String url, String title, String imgUrl, final String myTransaction) {
        if (!BaseApplication.getWxApi().isWXAppInstalled()) {
            ToastUtils.showToast("您还没安装微信应用");
            return;
        }
        //初始化WXWebpageObject对象,填写url
        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        //用WXWebpageObject初始化一个WXMediaMessage的对象,填写标题和描述、以及小图标
        wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.title = title;
        Glide.with(mContext).load(imgUrl).into(new SimpleTarget() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition transition) {
                Bitmap bitmap = ImagUtils.drawableToBitmap(resource);
                //设置缩略图
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 80, 80, true);
                wxMediaMessage.setThumbImage(scaledBitmap);
                //构造一个req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                //transaction字段唯一
                req.transaction = myTransaction;
                req.message = wxMediaMessage;
                //分享到朋友圈
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                //调用微信接口分享
                BaseApplication.getWxApi().sendReq(req);
            }
        });
    }

    /**
     * 分享图片到朋友圈
     *
     * @param bitmap
     */
    public static void shareImgeToFriends(Bitmap bitmap) {
        if (!BaseApplication.getWxApi().isWXAppInstalled()) {
            ToastUtils.showToast("您还没安装微信应用");
            return;
        }
        if (bitmap==null) {
            return;
        }
        //初始化WXWXImageObject对象和WXMediaMessage对象
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        WXMediaMessage wxMediaMessage = new WXMediaMessage();
        wxMediaMessage.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 50, 100, true);
        wxMediaMessage.setThumbImage(scaledBitmap);

        //构造一个req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        //transaction字段唯一
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = wxMediaMessage;
        //分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        //调用微信接口分享
        BaseApplication.getWxApi().sendReq(req);
    }

    /**
     * 分享图片给朋友
     *
     * @param bitmap
     */
    public static void shareImgeToMyFriend(Bitmap bitmap) {
        if (!BaseApplication.getWxApi().isWXAppInstalled()) {
            ToastUtils.showToast("您还没安装微信应用");
            return;
        }
        if (bitmap==null) {
            return;
        }
        //初始化WXWXImageObject对象和WXMediaMessage对象
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        WXMediaMessage wxMediaMessage = new WXMediaMessage();
        wxMediaMessage.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 50, 100, true);
        wxMediaMessage.setThumbImage(scaledBitmap);

        //构造一个req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        //transaction字段唯一
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = wxMediaMessage;
        //分享给我的朋友
        req.scene = SendMessageToWX.Req.WXSceneSession;
        //调用微信接口分享
        BaseApplication.getWxApi().sendReq(req);
    }
    /**
     * 小程序类型分享
     */
    public static void shareProgramObject(String title,String path){
        if (!BaseApplication.getWxApi().isWXAppInstalled()) {
            ToastUtils.showToast("您还没安装微信应用");
            return;
        }
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = "http://www.hellokeeper.com/lsf/client-download.html"; // 兼容低版本的网页链接
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0,测试版:1,体验版:2
        miniProgramObj.userName = "gh_ee782e862a53";     // 小程序原始id
        miniProgramObj.path = path;            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = title;                    // 小程序消息title
        msg.description = "小程序消息Desc";               // 小程序消息desc
        Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.getCurrentActivity().getResources(), R.mipmap.mini_banner1);
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 833, 666, true);
        msg.setThumbImage(scaledBitmap);                     // 小程序消息封面图片,小于128k
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = ("miniProgram");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
        BaseApplication.getWxApi().sendReq(req);
    }
}

5.微信支付的工具类

public class WXpayUtils {
    /**
     *调起微信支付的方法
     **/
    public static void toWXPay( final String partnerId, final String prepayId, final String nonceStr,
                               final String timeStamp, final String sign, final String packageValue, final String tag) {
        if (! BaseApplication.getWxApi().isWXAppInstalled()) {
            ToastUtils.showToast("你没有安装微信");
            return;
        }
        //一定注意要放在子线程
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信的对象

                //这几个参数的值,正是上面我们说的统一下单接口后返回来的字段,我们对应填上去即可
                request.appId = Configure.WX_AppID;
                request.partnerId = partnerId;
                request.prepayId = prepayId;
                request.packageValue = packageValue;
                request.nonceStr = nonceStr;
                request.timeStamp = timeStamp;
                request.sign = sign;
                //设置标识
                request.extData = tag;
                BaseApplication.getWxApi().sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}

你可能感兴趣的:(安卓开发)