美文网首页Android技术分享交流区
APP常见的三种支付方式

APP常见的三种支付方式

作者: 8beccf48629a | 来源:发表于2018-01-06 15:02 被阅读291次

    很久没写文章了,现在市面上大部分的应用都集成了第三方支付平台,有道云笔记里整理了一下之前写的代码。代码有点乱,大家看看见怪不怪哈。。

     public abstract class BasePayActivity extends BaseActivity {
        //订单类支付;支付失败转向订单详情
        public static final int TYPE_ORDER = 10;
        //充值类支付;支付失败转向本页面
        public static final int TYPE_RECHARGE = 20;
        //打赏类支付;支付失败转向本页面;支付成功界面显示跳转与以上两种类型略有不同
        public static final int TYPE_REWARD = 30;
        protected static final int SDK_PAY_FLAG = 1;
        private static final int SDK_CHECK_FLAG = 2;
    
        /*****************************************************************
         * mMode参数解释: "00" - 启动银联正式环境 "01" - 连接银联测试环境
         *****************************************************************/
        private final String mUnionPayMode = "01";
    
        protected RelativeLayout zfbPay;
        protected RelativeLayout weixinPay;
        protected TextView orderPriceTv;
        protected TextView orderRateCommit;
        protected ImageView ivAlipayFlag;
        protected ImageView ivWeixinFlag;
        //支付方式
        protected int mPayment = PaymentType.ALIPAY.getValue();
        protected OrderPresenter orderPresenter;
        protected String orderId;
        //订单金额
        protected String orderAmount;
        //账户余额
        protected double vipCardAccount;
        //支付类型
        protected int payType = TYPE_ORDER;
        protected ImageView ivVipFlag;
        protected TextView tvTotalPriceTitle;
        protected TextView tvVipAccount;
        protected View rlVipCard;
        //订单总计描述
        protected String orderTotalDesc;
        protected int shopId;
        protected List<Integer> serviceIds;
        protected View posPay;
        protected ImageView ivPosFlag;
        protected Handler mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);
                        // 支付宝返回此次支付结果及加签,建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
    //                    String resultInfo = payResult.getResult();
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            MobclickAgent.onEvent(mActivity, UMEventKey.PAY_SUCCESS);
                            MobclickAgent.onEvent(mActivity, UMEventKey.ON_LINE_PAY);
                            ConvMobiSDK.orderPaySucc(BaseApplication.getId() + "",BaseApplication.getInstance().order);
                            showToast("支付成功");
                            paySuccess();
                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
                            if (TextUtils.equals(resultStatus, "8000")) {
                                showToast("支付结果确认中");
                                hideLoading();
                            } else {
                                // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
                                showToast("支付失败");
                                hideLoading();
                            }
                            if (payType == TYPE_ORDER) {
                                payFail();
                            }
                        }
                        break;
                    }
                    case SDK_CHECK_FLAG: {
                        showToast("检查结果为:" + msg.obj);
                        break;
                    }
                    default:
                        break;
                }
            }
        };
    
    
        protected abstract void payFail();
    
        protected boolean isWXPay() {
            return mPayment == PaymentType.WECHAT.getValue() || mPayment == PaymentType.WECHAT_APP_SHOPKEEPER.getValue();
        }
    
        protected abstract String getPayOrderDataSetType();
    
        protected abstract void paySuccess();
    
        @Override
        protected void setLayout() {
            setContentView(R.layout.activity_order_pay);
        }
    
        @Override
        protected void findViews() {
            setTopBarTitle("在线支付");
            zfbPay = (RelativeLayout) findViewById(R.id.zfb_pay);
            zfbPay.setOnClickListener(this);
    
            weixinPay = (RelativeLayout) findViewById(R.id.weixin_pay);
            weixinPay.setOnClickListener(this);
    
            posPay = findView(R.id.pos_pay);
            posPay.setOnClickListener(this);
    
            orderPriceTv = (TextView) findViewById(R.id.order_price);
            orderRateCommit = (TextView) findViewById(R.id.order_rate_commit);
            orderRateCommit.setOnClickListener(this);
    
            ivAlipayFlag = (ImageView) findViewById(R.id.iv_alipay_flag);
            ivWeixinFlag = (ImageView) findViewById(R.id.iv_weixin_flag);
            ivPosFlag = findView(R.id.iv_pos_flag);
    
            rlVipCard = findViewById(R.id.rl_vip_card);
    
            ivVipFlag = findView(R.id.iv_vip_flag);
            tvTotalPriceTitle = findView(R.id.tv_total_price_title);
            tvVipAccount = findView(R.id.tv_vip_account);
            if (!TextUtils.isEmpty(orderAmount)) {
                orderPriceTv.setText(orderAmount.replaceAll("\\.0+$", ""));
            }
            if (!TextUtils.isEmpty(orderTotalDesc)) {
                tvTotalPriceTitle.setText(orderTotalDesc);
            } else {
                if (payType == TYPE_ORDER) {
                    tvTotalPriceTitle.setText("订单总价");
                } else {
                    tvTotalPriceTitle.setText("门店充值卡");
                }
            }
    
        }
    
        @Override
        protected void setListeners() {
    
        }
    
        @Override
        protected void initDatas() {
            orderPresenter = new OrderPresenter(this);
            payType = getIntent().getIntExtra(Extra.PAY_TYPE, TYPE_ORDER);
            vipCardAccount = getIntent().getDoubleExtra(Extra.VIP_CARD_ACCOUNT, 0);
            orderId = getIntent().getStringExtra(Extra.ORDER_ID);
    
            orderAmount = getIntent().getStringExtra(Extra.AMOUNT);
            orderTotalDesc = getIntent().getStringExtra(Extra.ORDER_TOTAL_DESC);
    
            //购物车支付成功后,清除相应购物车中的数据
            shopId = getIntent().getIntExtra(Extra.SHOP_ID, 0);
            serviceIds = getIntent().getIntegerArrayListExtra(Extra.ITEM_ID);
        }
    
        @Override
        public boolean isShowTopBar() {
            return true;
        }
    
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.rl_vip_card) {
                selectVipCard();
            } else if (id == R.id.zfb_pay) {
                selectAlipay();
            } else if (id == R.id.weixin_pay) {
                selectWeixin();
            } else if (id == R.id.pos_pay) {
                selectPos();
            } else if (id == R.id.order_rate_commit) {
                MobclickAgent.onEvent(this, UMEventKey.CLICK_PAY_BUTTON);
                if (mPayment != 0) {
                    payOrder();
                } else {
                    showToast("请选择支付方式");
                }
            }
        }
    
        protected abstract void payOrder();
    
        protected void selectPos() {
            ivVipFlag.setImageResource(R.drawable.ic_choose_gray);
            ivWeixinFlag.setImageResource(R.drawable.ic_choose_gray);
            ivAlipayFlag.setImageResource(R.drawable.ic_choose_gray);
            ivPosFlag.setImageResource(R.drawable.ic_choose_red);
            mPayment = PaymentType.POS.getValue();
        }
    
        protected void selectWeixin() {
            ivVipFlag.setImageResource(R.drawable.ic_choose_gray);
            ivWeixinFlag.setImageResource(R.drawable.ic_choose_red);
            ivAlipayFlag.setImageResource(R.drawable.ic_choose_gray);
            ivPosFlag.setImageResource(R.drawable.ic_choose_gray);
            mPayment = PaymentType.WECHAT.getValue();
        }
    
        protected void selectAlipay() {
            ivVipFlag.setImageResource(R.drawable.ic_choose_gray);
            ivWeixinFlag.setImageResource(R.drawable.ic_choose_gray);
            ivPosFlag.setImageResource(R.drawable.ic_choose_gray);
            ivAlipayFlag.setImageResource(R.drawable.ic_choose_red);
            mPayment = PaymentType.ALIPAY.getValue();
        }
    
        protected void selectVipCard() {
            ivVipFlag.setImageResource(R.drawable.ic_choose_red);
            ivWeixinFlag.setImageResource(R.drawable.ic_choose_gray);
            ivAlipayFlag.setImageResource(R.drawable.ic_choose_gray);
            ivPosFlag.setImageResource(R.drawable.ic_choose_gray);
            mPayment = PaymentType.MEININGJIA_CARD.getValue();
        }
    
        protected void selectUPPay() {
            ivVipFlag.setImageResource(R.drawable.ic_choose_gray);
            ivWeixinFlag.setImageResource(R.drawable.ic_choose_gray);
            ivAlipayFlag.setImageResource(R.drawable.ic_choose_gray);
            ivPosFlag.setImageResource(R.drawable.ic_choose_gray);
            mPayment = PaymentType.UNION_PAY.getValue();
        }
    
        @Override
        public void onClickTopBarLeft() {
            if (payType == TYPE_ORDER) {
                payFail();
            }
            super.onClickTopBarLeft();
        }
    
        @Override
        public void setResultData(String dataSetType, Object object) {
            final String payInfo = getPayInfo(object);
            //无需支付判断
            if (TextUtils.isEmpty(payInfo)) {
                showToast("亲,该笔订单支付成功");
                paySuccess();
                return;
            }
            if (getPayOrderDataSetType().equals(dataSetType)) {
                if (PaymentType.UNION_PAY.getValue() == this.mPayment) {
                    unionPayResultData();
                } else if (PaymentType.POS.getValue() == this.mPayment) {
                    POSResultData();
                } else if (PaymentType.ALIPAY.getValue() == this.mPayment) {
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            //构建PayTask对象
                            PayTask payTask = new PayTask(mActivity);
                            //调用支付接口,获取支付的结果
                            String result = payTask.pay(payInfo, true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } else if (isWXPay()) {
                    Map<String, String> payReqMap = JsonUtil.json2Map(payInfo, new TypeToken<Map<String, String>>() {
                    });
                    if (payReqMap == null) {
                        showToast(payInfo);
                        return;
                    }
                    JSONObject jsonObject = getWXPayInfo();
                    payReqMap.put(Extra.EXTRA, jsonObject.toString());
                    WeixinPay.getInstance(this).sendPayReq(payReqMap);
                    this.finish();
                }
            }
        }
    
        protected abstract String getPayInfo(Object object);
    
        protected void unionPayResultData() {
    //        if (!UPPayAssistEx.checkInstalled(mActivity)) {
    //            //当判断用户手机上已安装银联Apk,商户客户端可以做相应个性化处理
    //            showCenterToast("请安装银联支付");
    //            return;
    //        }
            //TODO
            String tn = "此处放银联收款账号";
            UPPayAssistEx.startPay(mActivity, null, null, tn, mUnionPayMode);
        }
    
        protected void POSResultData() {
            Bundle bundle = new Bundle();
            bundle.putString(Extra.ORDER_NUM, orderId);
            bundle.putString(Extra.AMOUNT, orderAmount);
            bundle.putInt(Extra.PAY_TYPE, getIntent().getIntExtra(Extra.PAY_TYPE, TYPE_ORDER));
            IntentUtil.startActivity(mActivity, POSPayActivity.class, bundle);
            finish();
        }
    
        protected abstract JSONObject getWXPayInfo();
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            /*************************************************
             * 步骤3:处理银联手机支付控件返回的支付结果
             ************************************************/
            if (data == null) {
                return;
            }
            String msg = "";
            /*
             * 支付控件返回字符串:success、fail、cancel 分别代表支付成功,支付失败,支付取消
             */
            String str = data.getExtras().getString("pay_result");
            if (str.equalsIgnoreCase("success")) {
                // 如果想对结果数据验签,可使用下面这段代码,但建议不验签,直接去商户后台查询交易结果
                // result_data结构见c)result_data参数说明
                if (data.hasExtra("result_data")) {
                    String result = data.getExtras().getString("result_data");
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        String sign = resultJson.getString("sign");
                        String dataOrg = resultJson.getString("data");
                        // 此处的verify建议送去商户后台做验签
                        // 如要放在手机端验,则代码必须支持更新证书
                        boolean ret = verify(dataOrg, sign, mUnionPayMode);
                        if (ret) {
                            // 验签成功,显示支付结果
                            msg = "支付成功!";
                        } else {
                            // 验签失败
                            msg = "支付失败!";
                        }
                    } catch (Exception e) {
                    }
                }
                // 结果result_data为成功时,去商户后台查询一下再展示成功
                msg = "支付成功!";
            } else if (str.equalsIgnoreCase("fail")) {
                msg = "支付失败!";
            } else if (str.equalsIgnoreCase("cancel")) {
                msg = "用户取消了支付";
            }
    
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("支付结果通知");
            builder.setMessage(msg);
            builder.setInverseBackgroundForced(true);
            // builder.setCustomTitle();
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    
        private boolean verify(String msg, String sign64, String mode) {
            // 此处的verify,商户需送去商户后台做验签
            return true;
        }
    

    由于是早期的代码写的不好的地方希望大家多多包涵,如果能给大家带来帮助当然更好,有问题请提出您的宝贵意见。

    相关文章

      网友评论

        本文标题:APP常见的三种支付方式

        本文链接:https://www.haomeiwen.com/subject/itsynxtx.html