接入支付宝刷脸支付

在接入之前先看下文档支付宝扫脸接入文档,

https://docs.open.alipay.com/20180402104715814204/intro

https://doc.open.alipay.com/docs/doc.htm?docType=1&articleId=108568

这里一定要详细了解官方提供的API,问下支付宝那边的文档是不是最新的,避免一些不必要的坑.

接入
第一步:创建应用(后台)
第二步:配置密钥(后台)
第三步:搭建和配置开发环境(后台)
1.下载服务端SDK(后台)
2.接口调用配置(后台)
第四步:接口调用(前端)

这里就不细说了, API上都有说明,大家看看就明白了

技术接入流程图:

添加项目依赖:

第一个我用来请求数据,第二个我用来解析数据第三个是支付宝api那里的下载

(这里说一下,我项目之前用的是Rxjava,在对应的位置写请求,报线程错误,在子线程也是报这个错,所以就用async来请求,结果是可以)

在MerchantInfo配置自己需要的数据

看需求填写自己的所需数据参数

看需求填写自己的所需数据参数

在这个位置请求自己服务器的刷脸接口

这里自己写的用android-async-http-master.jar请求数据用fastJson-1.1.45.jar解析

然后

//获取zimId和zimInitClientData调用人脸初始化
String zimId = products.get(0).getZimId();
String zimInitClientData = products.get(0).getZimInitClientData();
smile(zimId, zimInitClientData);
Log.e("TAG", "zimid----------------"+zimId);
Log.e("TAG", "zimInitClientData----------------"+zimInitClientData);
/**
     * 发起刷脸支付请求.
     * @param zimId 刷脸付token,从服务端获取,不要mock传入
     * @param protocal 刷脸付协议,从服务端获取,不要mock传入
     */
    //. 唤起人脸识别
    private void smile(String zimId, String protocal) {
        Map params = new HashMap();
        params.put(KEY_INIT_RESP_NAME, protocal);

       //个询问支付宝那边的.我也不知道干嘛用的
        /* start: 如果是预输入手机号方案,请加入以下代码,填入会员绑定的手机号,必须与支付宝帐号对应的手机号一致 */
        params.put("phone_number", "1381XXXXX");
        /* end: --------------------------------------------- */
        zoloz.zolozVerify(zimId, params, new ZolozCallback() {
            @Override
            public void response(final Map smileToPayResponse) {
                if (smileToPayResponse == null) {
//                    promptText("2----------"+TXT_OTHER);
                    return;
                }
                String code = (String)smileToPayResponse.get("code");
                String fToken = (String)smileToPayResponse.get("ftoken");
                String subCode = (String)smileToPayResponse.get("subCode");
                String msg = (String)smileToPayResponse.get("msg");
                Log.e("TAG", "ftoken is:-----------" + fToken);
                Log.e("TAG", "code is:-----------" + code);
                Log.e("TAG", "subCode is:-----------" + subCode);
                Log.e("TAG", "msg is:-----------" + msg);

                //刷脸成功
                if (CODE_SUCCESS.equalsIgnoreCase(code) && fToken != null) {
                    //promptText("刷脸成功,返回ftoken为:" + fToken);
                    //这里在Main线程,网络等耗时请求请放在异步线程中
                    //后续这里可以发起支付请求
                    //https://docs.open.alipay.com/api_1/alipay.trade.pay
                    //需要修改两个参数
                    //scene固定为security_code
                    //auth_code为这里获取到的fToken值
                    //支付一分钱,支付需要在服务端发起,这里只是模拟

                    sharedPreference = ISharedPreference.getInstance(getApplication());//获取保存的token
                    //联网发送信息给服务器(自己的服务器)
                    String register = "http://test.shanghkj.com/api/merchant/SmTradePay";
                    //这里是要传送的参数
                    RequestParams params = new RequestParams();
                    params.put("token",sharedPreference.getToken());
                    params.put("remark",dataBinding.generalNote.getText().toString());//备注
                    params.put("code",fToken);//传ftonen
                    params.put("total_amount",dataBinding.generalCount.getText().toString());//金额
                    params.put("desc","描述");
                    Log.e("TAG", "token------"+sharedPreference.getToken());
                    Log.e("TAG", "remark------"+dataBinding.generalNote.getText().toString());
                    Log.e("TAG", "fToken------"+fToken);
                    Log.e("TAG", "dataBinding.generalCount.getText().toString()------"+dataBinding.generalCount.getText().toString());
                    Log.e("TAG", "desc------");
                    client.post(register, params, new AsyncHttpResponseHandler(){
                        @Override
                        public void onSuccess(String content) {
                            Log.e("TAG", "content---第二步的成功-------------"+content);
                        }

                        @Override
                        public void onFailure(Throwable error, String content) {
                            Log.e("TAG", "content-------第二步的失败---------"+content);
                        }
                    });
                }
            }

        });
    }

然后就对接到第三步了就完成简单的支付了

因为涉及敏感字段

第四步,第五步,建议在服务端实现




public class GeneralActivity extends BaseActivity<FragmentGeneralBinding> implements View.OnClickListener {

    private static final String TAG = GeneralActivity.class.getSimpleName();
    private static final int SCAN_CODE = 100;//扫码requestCode
    private static final int SCAN_PAY_CODE = 101;//扫码付款
    private static final int BANK_CODE = 102;//银行卡收款  调起支付页面
    private RxPermissions permissions;//权限申请
    private BillViewModel model;
    private ProgressDialog dialog;
    private ProgressDialog bankDialog;
    private Intent bankIntent;
    private BankViewModel bankViewModel;



    //使用AsyncHttpClient,实现联网的声明
    public AsyncHttpClient client = new AsyncHttpClient();




    private boolean scanPay = false;//是否是扫码收款
  public GeneralActivity(){}

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_general;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//扫脸用的,要是不行就放在首页开始初始化
        zoloz = com.alipay.zoloz.smile2pay.service.Zoloz.getInstance(getApplicationContext());
        //初始化打印机
        AidlUtil.getInstance().initPrinter();

        if (mImmersionBar != null)
            mImmersionBar.titleBar(dataBinding.norGatherToolbar).init();
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        permissions = new RxPermissions(this);

        //设置点击事件
        dataBinding.collectionList.setOnClickListener(this);
        dataBinding.norGatherToolbar.setNavigationOnClickListener(v -> {
            closeKeyBoard();
            onBackPressed();
        });

        dataBinding.collectionSearch.setOnClickListener(this);
        dataBinding.sweep.setOnClickListener(this);
        dataBinding.sweepReceive.setOnClickListener(this);
        dataBinding.bankCardReceive.setOnClickListener(this);
        dataBinding.fristDepositList.setOnClickListener(this);//押金收款
        
        
        
        
        dataBinding.generalCount.setFilters(new InputFilter[]{new AmountFilter()});
        showKeyBoard(dataBinding.generalCount);

        if (SystemUtil.getSystemModel().contains("P1")) {

            dataBinding.bankCardReceive.setVisibility(View.VISIBLE);
        } else {
            dataBinding.bankCardReceive.setVisibility(View.GONE);
        }
        //初始化参数  调起银行卡相关支付
        initIntent();
        //snackbar
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                if (s.contains("等待用户支付超时") || s.contains("订单未支付")) {
                    showDepositDely(s);
                } else {
                    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
                }
            }

        });
        //dialog
        model.dialogText.observe(this, s -> {
            if (s == null) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            } else {
                dialog = ProgressDialog.show(this, "正在交易...", s, false);
            }
        });
        //snackbar
        bankViewModel.snackText.observe(this, s -> {
            if (s != null) {
                if (s.contains("等待用户支付超时") || s.contains("订单未支付")) {
                    showDepositDely(s);
                } else
                    Snackbar.make(dataBinding.generalNoteLay, s, Snackbar.LENGTH_SHORT).show();
            }

        });
        //dialog
        bankViewModel.dialogText.observe(this, s -> {
            if (s == null) {
                if (bankDialog != null) {
                    bankDialog.dismiss();
                }
            } else {
                bankDialog = ProgressDialog.show(this, "请稍等...", s, false);
            }
        });
    }

    //显示支付超时dialog
    private void showDepositDely(String content) {

        ViewDialog dialog = new ViewDialog();
        dialog.setLayoutId(R.layout.deposit_dialog);
        dialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.accept_dialog_title);
            TextView ok = view.findViewById(R.id.ok);

            if (content.contains("等待用户支付超时")) {
                String result = String.valueOf(Html.fromHtml(content));
                int start = result.indexOf("(");
                int end = result.indexOf(")");
                SpannableStringBuilder spannableString = new SpannableStringBuilder(result);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FE4655")),
                        start + 1, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                title.setText(spannableString);
            } else if (content.contains("订单未支付")) {
                title.setText(content);
            }


            ok.setOnClickListener(v -> dialog.dismiss());
        });
        dialog.show(getSupportFragmentManager(), "0");
    }

    //显示键盘
    private void showKeyBoard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Objects.requireNonNull(imm).showSoftInput(editText, 0);
                editText.setSelection(editText.getText().length());
            }
        }, 200);
    }

    //关闭软键盘
    private void closeKeyBoard() {

        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getWindow().peekDecorView();
        if (view != null) {
            if (Objects.requireNonNull(manager).isActive()) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }

    }

    //抽取各个交易类型公共的字段
    private void initIntent() {
        bankIntent = new Intent();
        bankIntent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk",
                "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        bankIntent.putExtra("appId", this.getPackageName());
    }

    //关闭软键盘
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeKeyBoard();
        }
        return super.onKeyDown(keyCode, event);
    }

    //将交易金额统一处理成12位,不足12位的在前面补0
    private String getAmount(String amount) {
        if (TextUtils.isEmpty(amount)) return null;
        while (amount.length() < 12) {
            amount = "0" + amount;
        }
        return amount;
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            //扫一扫查询订单
            case R.id.sweep:
                requestScanPermission(SCAN_CODE);
                break;
            case R.id.frist_deposit_list:
//                intent = new Intent(GeneralActivity.this, DepositActivity.class);
//                startActivity(intent);
//                finish();
                Log.e("TAG", "去往扫脸收银");
                if (TextUtils.isEmpty(dataBinding.generalCount.getText().toString())) {
                    Snackbar.make(v, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                smilePay();
//                initFacePay();
                break;
            //收款列表
            case R.id.collection_list:
                intent = new Intent(GeneralActivity.this, GatherListActivity.class);
                startActivity(intent);
                break;

            //普通收款查询
            case R.id.collection_search:

                intent = new Intent(GeneralActivity.this, SearchGaActivity.class);
                startActivity(intent);
                break;


            //扫码收款
            case R.id.sweep_receive:

                if (TextUtils.isEmpty(dataBinding.generalCount.getText().toString())) {
                    Snackbar.make(v, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                requestScanPermission(SCAN_PAY_CODE);

                break;

            case R.id.bank_card_receive:
                if (TextUtils.isEmpty(dataBinding.generalCount.getText().toString())) {
                    Snackbar.make(v, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (!ClickUtil.isFasClick()) {
                    bankViewModel.createBankOrder(Double.parseDouble(dataBinding.generalCount.getText().toString()),
                            "pay", dataBinding.generalNote.getText().toString(),
                            0, "0", () -> {
//                            dialog.dismiss();
                                Log.e("TAG", "onClick: 创建普通收款订单成功:");
                                startGather();
                            });
                }
                //创建普通银行卡收款订单
                break;
        }

    }

    /*----------------------------扫脸--------------------------------我是分割线--------------以下------------------扫脸---------------------------------------------------*/
    /**
     * 发起刷脸支付请求,先zolozGetMetaInfo获取本地app信息,然后调用服务端获取刷脸付协议.
     */


    // 值为"1000"调用成功
    // 值为"1003"用户选择退出
    // 值为"1004"超时
    // 值为"1005"用户选用其他支付方式
    static final String CODE_SUCCESS = "1000";
    static final String CODE_EXIT = "1003";
    static final String CODE_TIMEOUT = "1004";
    static final String CODE_OTHER_PAY = "1005";

    static final String TXT_EXIT = "已退出刷脸支付";
    static final String TXT_TIMEOUT = "操作超时";
    static final String TXT_OTHER_PAY = "已退出刷脸支付";
    static final String TXT_OTHER = "抱歉未支付成功,请重新支付";

    //刷脸支付相关
    static final String SMILEPAY_CODE_SUCCESS = "10000";
    static final String SMILEPAY_SUBCODE_LIMIT = "ACQ.PRODUCT_AMOUNT_LIMIT_ERROR";
    static final String SMILEPAY_SUBCODE_BALANCE_NOT_ENOUGH = "ACQ.BUYER_BALANCE_NOT_ENOUGH";
    static final String SMILEPAY_SUBCODE_BANKCARD_BALANCE_NOT_ENOUGH = "ACQ.BUYER_BANKCARD_BALANCE_NOT_ENOUGH";

    static final String SMILEPAY_TXT_LIMIT = "刷脸支付超出限额,请选用其他支付方式";
    static final String SMILEPAY_TXT_EBALANCE_NOT_ENOUGH = "账户余额不足,支付失败";
    static final String SMILEPAY_TXT_BANKCARD_BALANCE_NOT_ENOUGH = "账户余额不足,支付失败";
    static final String SMILEPAY_TXT_FAIL = "抱歉未支付成功,请重新支付";
    static final String SMILEPAY_TXT_SUCCESS = "刷脸支付成功";
    private Zoloz zoloz;
    private ISharedPreference sharedPreference;
    private List<FacePayBean.DataBean> products;

    private void smilePay() {
        zoloz.zolozGetMetaInfo(mockInfo(), new ZolozCallback() {
            // 解析zolozGetMetaInfo返回的结果,如果成功,则请求商户服务端调用人脸初始化接口
            @Override
            public void response(Map smileToPayResponse) {
                if (smileToPayResponse == null) {
                    Log.e("TAG", "response is null");
//                    promptText("5----------"+TXT_OTHER);
                    return;
                }
                String code = (String)smileToPayResponse.get("code");
                String  metaInfo = (String)smileToPayResponse.get("metainfo");
                Log.e("TAG", "code----------------"+code);//1000值为"1000"调用成功
                Log.e("TAG", "metaInfo----------------"+metaInfo);
                //获取metainfo成功
                if (CODE_SUCCESS.equalsIgnoreCase(code) && metaInfo != null) {
//                    2. 刷脸初始化
                    //这里用Rxjava 联网请求报线程错误
                    //然后找了两个个jar包android-async-http-master.jar和fastJson-1.1.45.jar
                    //android-async-http-master.jar请求数据用fastJson-1.1.45.jar解析
                    Log.e("TAG", "-------获取metainfo成功并开始初始化人脸----"+metaInfo);
                    sharedPreference = ISharedPreference.getInstance(getApplication());//获取保存的token
                    //联网发送信息给服务器(自己的服务器)
                    String register = "http://test.shanghkj.com/api/merchant/smilepayInit";
                    //这里是要传送的参数
                    RequestParams params = new RequestParams();
                    params.put("token",sharedPreference.getToken());
                    params.put("all",metaInfo);
                    //开始联网请求
                    client.post(register,params ,new AsyncHttpResponseHandler(){
                        //成功
                        @Override
                        public void onSuccess(String content) {
                            Log.e("TAG", "woyao chenggh 安居客符号化---------"+content);
                            //这里去解析数据content
                            JSONObject jsonObject = JSON.parseObject(content);
                            String proInfo = jsonObject.getString("data");
                            products = JSON.parseArray(proInfo, FacePayBean.DataBean.class);
                            Log.e("TAG", "product------getZimInitClientData---------"+products.get(0).getZimInitClientData());
                            Log.e("TAG", "product-----getZimId----------"+products.get(0).getZimId());
                            Log.e("TAG", "product-------getMsg--------"+products.get(0).getMsg());
                            Log.e("TAG", "product--------getType-------"+products.get(0).getType());
                            Log.e("TAG", "product-------getStore_name--------"+products.get(0).getStore_name());


                            //获取zimId和zimInitClientData调用人脸初始化
                            String zimId = products.get(0).getZimId();
                            String zimInitClientData = products.get(0).getZimInitClientData();
                            smile(zimId, zimInitClientData);//唤起人脸识别
                            Log.e("TAG", "zimid----------------"+zimId);
                            Log.e("TAG", "zimInitClientData----------------"+zimInitClientData);

                            //这个我也不知道干嘛的,好像不能注释
                            UIUtils.getHandler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
//                                    removeCurrentActivity();//销毁当前的activity
                                }
                            },2000);
                        }
                        @Override
                        public void onFailure(Throwable error, String content) {
                            Toast.makeText(GeneralActivity.this, "网络异常,调用失败!", Toast.LENGTH_SHORT).show();

                        }
                    } );
                }
          }
       });
    }
    public static final String KEY_INIT_RESP_NAME = "zim.init.resp";
    /**
     * 发起刷脸支付请求.
     * @param zimId 刷脸付token,从服务端获取,不要mock传入
     * @param protocal 刷脸付协议,从服务端获取,不要mock传入
     */
    //. 唤起人脸识别
    private void smile(String zimId, String protocal) {
        Map params = new HashMap();
        params.put(KEY_INIT_RESP_NAME, protocal);
        Log.e("TAG", "protocal----protocal---protocal---"+protocal);
        Log.e("TAG", "zimId----zimId---zimId---"+zimId);
       //个询问支付宝那边的.我也不知道干嘛用的
        /* start: 如果是预输入手机号方案,请加入以下代码,填入会员绑定的手机号,必须与支付宝帐号对应的手机号一致 */
//        这句代码就是扫脸之后会有一个用户输入手机号的页面,您要是写这一行,就不需要用户去手动输入,会直接把用户手机号显示在页面,
// 不写的话需要用户手动去输入
//        params.put("phone_number", "1381XXXXX");
        /* end: --------------------------------------------- */
        zoloz.zolozVerify(zimId, params, new ZolozCallback() {
            @Override
            public void response(final Map smileToPayResponse) {
                if (smileToPayResponse == null) {
//                    promptText("2----------"+TXT_OTHER);
                    Toast.makeText(GeneralActivity.this, TXT_OTHER, Toast.LENGTH_SHORT).show();
                    return;
                }
                String code = (String)smileToPayResponse.get("code");
                String fToken = (String)smileToPayResponse.get("ftoken");
                String subCode = (String)smileToPayResponse.get("subCode");
                String msg = (String)smileToPayResponse.get("msg");
                Log.e("TAG", "ftoken is:-----------" + fToken);
                Log.e("TAG", "code is:-----------" + code);
                Log.e("TAG", "subCode is:-----------" + subCode);
                Log.e("TAG", "msg is:-----------" + msg);

                //刷脸成功
                if (CODE_SUCCESS.equalsIgnoreCase(code) && fToken != null) {
                    //promptText("刷脸成功,返回ftoken为:" + fToken);
                    //这里在Main线程,网络等耗时请求请放在异步线程中
                    //后续这里可以发起支付请求
                    //https://docs.open.alipay.com/api_1/alipay.trade.pay
                    //需要修改两个参数
                    //scene固定为security_code
                    //auth_code为这里获取到的fToken值
                    //支付一分钱,支付需要在服务端发起,这里只是模拟

                    sharedPreference = ISharedPreference.getInstance(getApplication());//获取保存的token
                    //联网发送信息给服务器(自己的服务器)
                    String register = "http://test.shanghkj.com/api/merchant/SmTradePay";
                    //这里是要传送的参数
                    RequestParams params = new RequestParams();
                    params.put("token",sharedPreference.getToken());
                    params.put("remark",dataBinding.generalNote.getText().toString());//备注
                    params.put("code",fToken);//传ftonen
                    params.put("total_amount",dataBinding.generalCount.getText().toString());//金额
                    params.put("desc","描述");
                    Log.e("TAG", "token------"+sharedPreference.getToken());
                    Log.e("TAG", "remark------"+dataBinding.generalNote.getText().toString());
                    Log.e("TAG", "fToken------"+fToken);
                    Log.e("TAG", "dataBinding.generalCount.getText().toString()------"+dataBinding.generalCount.getText().toString());
                    Log.e("TAG", "desc------");
                    client.post(register, params, new AsyncHttpResponseHandler(){
                        @Override
                        public void onSuccess(String content) {
                            Log.e("TAG", "content---第二步的成功-------------"+content);


                            ScanPayBean scanPayBean = model.scanPay.get();
                            if (scanPayBean != null) {
                                print(scanPayBean);
                                String contentSm = "扫脸收款成功  ¥" + dataBinding.generalCount.getText().toString() + " " + getCurrentTime();
                                //显示打印dialog
                                showPrintDialog(scanPayBean);
                                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "尚瀚支付推送提醒", contentSm, () -> {

                                });
                            }
                        }

                        @Override
                        public void onFailure(Throwable error, String content) {
                            Log.e("TAG", "content-------第二步的失败---------"+content);
                        }
                    });
                }
            }

        });
    }
 /*----------------------------扫脸--------------------------------我是分割线----------以上----------------------扫脸---------------------------------------------------*/

    private void startGather() {
        if (bankViewModel.bankBean != null) {
            //获取订单成功后
            BankBean.DataBean bean = bankViewModel.bankBean.get();
            if (bean != null) {
                String str = bean.getAmount();
                double du = Double.valueOf(str) * 100;
                int result = (int) du;
                Log.d(TAG, "getInfo: 最后金额结果:" + result);
                bankIntent.putExtra("barcodeType", "0");//指定为银行卡消费
                bankIntent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                bankIntent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                bankIntent.putExtra("transName", "0");//交易订单号


                //用户联备注
                bankIntent.putExtra("printMerchantInfo",
                        "交易订单号:" + bean.getOut_trade_no() + "        "
                                + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("printMerchantInfo2", bean.getOut_trade_no());
                bankIntent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                        + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("priInfo2", bean.getOut_trade_no());
                //判断是否安装盛付通支付
                if (isInstallShengfuPay()) {
                    startActivityForResult(bankIntent, BANK_CODE);
                } else {
                    Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //判断是否安装盛付通支付sdk
    private boolean isInstallShengfuPay() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            if (SystemUtil.getSystemModel().equals("P1") || SystemUtil.getSystemModel().equals("P1_4G")) {
                if (list.get(i).packageName.equalsIgnoreCase("sunmi.fw2.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("sunmimi.payment.shengpay")) {

                    return true;
                }
            }
            Log.d(TAG, "isInstallShengfuPay: 包名:" + list.get(i).packageName);
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //处理二维码扫描结果
        if (requestCode == SCAN_CODE && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) return;

            dealWithScanResult(bundle);
        }

        //当为扫码付款时
        if (requestCode == SCAN_PAY_CODE && data != null) {
            Bundle bundle = data.getExtras();
            scanPay(bundle);
        }
        //这里处理银行卡收款  相关  交易成功 交易失败  进行回调
        if (requestCode == BANK_CODE && data != null) {
            Bundle extras1 = data.getExtras();

            bankPay(resultCode, extras1, data);

        }
    }


    /**
     * 处理二位扫描结果  查询订单
     *
     * @param bundle bundle
     */
    private void dealWithScanResult(Bundle bundle) {
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            if (result == null) {
                return;
            }
            boolean strHead = result.contains("fu");
            Log.e("TAG", "onActivityResult: 小票抬头是fu开头:" + strHead + "结果:" + result);
            if (result.startsWith("fu")) {//当时预授权订单时

                Intent intent = new Intent(GeneralActivity.this, AutTncActivity.class);
                intent.putExtra("orderId", result);
                startActivity(intent);

            } else {//否则是收款订单  或者分期订单   预授权结算后直接变成普通订单

                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", result);
                startActivity(intent);
            }

        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED)

        {
            Toast.makeText(GeneralActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }

    }

    //扫描二维码收款
    private void scanPay(Bundle bundle) {
        if (bundle == null) return;
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);

            if (result == null) {
                return;
            }
            //改变状态
            scanPay = true;
            //提交二维码扫描生成订单
            model.scanPay(dataBinding.generalNote.getText().toString(), result,
                    dataBinding.generalCount.getText().toString(), null, () -> {
                        dialog.dismiss();
                        //生成订单后 结束显示dialog
                        ScanPayBean scanPayBean = model.scanPay.get();
                        //支付成功后打印
                        if (scanPayBean != null) {
                            print(scanPayBean);
                            String content = "普通收款成功  ¥" + dataBinding.generalCount.getText().toString() + " " + getCurrentTime();
                            //显示打印dialog
                            showPrintDialog(scanPayBean);
                            model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "尚瀚支付推送提醒", content, () -> {

                            });
                        }
                    });

            Log.d(TAG, "onActivityResult: 解析结果:" + result);

        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            Toast.makeText(GeneralActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

    //显示打印dialog
    private void showPrintDialog(ScanPayBean scanPayBean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("收款成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            print.setOnClickListener(v -> {
                reprint(scanPayBean);
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
             //跳转到收款详情
                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", scanPayBean.getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }



    //打印
    private void print(ScanPayBean scanPayBean) {
        if (scanPayBean == null) {
            return;
        }

        List<String> printContent = Objects.requireNonNull(scanPayBean).getPrint_array();

        String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        aidlUtil.enterPrinterBuffer(true);
        int resId = 0;
        switch (bitmapType) {
            //支付宝支付
            case "0":
                resId = R.drawable.print_alipay;
                break;
            //微信支付
            case "1":
                resId = R.drawable.print_wx;
                break;
            //银行卡支付
            case "2":
                resId = R.drawable.print_unicon;

                break;
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
        //打印支付方式图标
        aidlUtil.printBitmap(bitmap, "2", "2");
        aidlUtil.printText(printContent.get(12),
                "24", "24", "1", false, false);
//        aidlUtil.printText("交易凭证重复打印",
//                "24", "24", "1", false, false);
        aidlUtil.printBlankLine("1", "10");
        //抬头
        aidlUtil.printText(printContent.get(1), "32", "32", "1",
                true, false);
        aidlUtil.printBlankLine("1", "10");
        //门店
        aidlUtil.printText(printContent.get(2), "24", "24", "1",
                false, false);
        aidlUtil.printBlankLine("1", "10");
        //订单支付方式text开始
        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
                "24", "24", "0",
                false, false);
        //业务记录
        aidlUtil.printText(printContent.get(4), "32", "32", "0",
                true, false);
        //业务记录内容
        aidlUtil.printText("\n" + printContent.get(5)
                        .replace("\\n", "\n"), "24", "24", "0",
                false, false);

        //退款 ||收款
        aidlUtil.printText("\n" + printContent.get(6), "32", "32", "0",
                true, false);
        //退款获取收款内容
        aidlUtil.printText("\n" + printContent.get(7)
                        .replace("\\n", "\n"), "24", "24", "0",
                false, false);
        aidlUtil.printBlankLine("1", "10");
        //打印二维码
        aidlUtil.printQr(printContent.get(8), "8", "3");
        //收银员   //打印时间
        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
                "24", "24", "0", false, false);
        aidlUtil.printBlankLine("1", "10");
        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
                "24", "24", "1", false, false);

        aidlUtil.printText("\n" + printContent.get(11).replace("\\n", "\n"),
                "24", "24", "1", false, false);

        aidlUtil.printBlankLine("5", "30");



        aidlUtil.printCommit();
    }
    //打印
    private void reprint(ScanPayBean scanPayBean) {
        if (scanPayBean == null) {
            return;
        }

        List<String> printContent = Objects.requireNonNull(scanPayBean).getPrint_array();

        String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        aidlUtil.enterPrinterBuffer(true);
        int resId = 0;
        switch (bitmapType) {
            //支付宝支付
            case "0":
                resId = R.drawable.print_alipay;
                break;
            //微信支付
            case "1":
                resId = R.drawable.print_wx;
                break;
            //银行卡支付
            case "2":
                resId = R.drawable.print_unicon;

                break;
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
        //打印支付方式图标
        aidlUtil.printBitmap(bitmap, "2", "2");
//        aidlUtil.printText(printContent.get(12),
//                "24", "24", "1", false, false);
        aidlUtil.printText("交易凭证重复打印",
                "24", "24", "1", false, false);
        aidlUtil.printBlankLine("2", "10");
        //抬头
        aidlUtil.printText(printContent.get(1), "32", "32", "1",
                true, false);
        aidlUtil.printBlankLine("1", "10");
        //门店
        aidlUtil.printText(printContent.get(2), "24", "24", "1",
                false, false);
        aidlUtil.printBlankLine("1", "10");
        //订单支付方式text开始
        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
                "24", "24", "0",
                false, false);
        //业务记录
        aidlUtil.printText(printContent.get(4), "32", "32", "0",
                true, false);
        //业务记录内容
        aidlUtil.printText("\n" + printContent.get(5)
                        .replace("\\n", "\n"), "24", "24", "0",
                false, false);

        //退款 ||收款
        aidlUtil.printText("\n" + printContent.get(6), "32", "32", "0",
                true, false);
        //退款获取收款内容
        aidlUtil.printText("\n" + printContent.get(7)
                        .replace("\\n", "\n"), "24", "24", "0",
                false, false);
        aidlUtil.printBlankLine("1", "10");
        //打印二维码
        aidlUtil.printQr(printContent.get(8), "8", "3");
        //收银员   //打印时间
        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
                "24", "24", "0", false, false);
        aidlUtil.printBlankLine("1", "10");
        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
                "24", "24", "1", false, false);

        aidlUtil.printText("\n" + printContent.get(11).replace("\\n", "\n"),
                "24", "24", "1", false, false);

        aidlUtil.printBlankLine("5", "30");



        aidlUtil.printCommit();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            return true;
        } else {
            return super.onTouchEvent(event);


        }
    }

    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");

        return simpleDateFormat.format(new Date());
    }

    //处理银行卡收款相关
    private void bankPay(int resultCode, Bundle extras1, Intent data) {
        boolean success = false;//是否交易成功
        if (extras1 == null) {
            return;
        }
        String payResult = null;//交易结果
        Set<String> keySet = extras1.keySet();
        switch (resultCode) {
            case Activity.RESULT_OK:
                Toast.makeText(GeneralActivity.this, "交易成功", Toast.LENGTH_SHORT).show();
                success = true;

                StringBuilder resultBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    resultBuilder.append(str);

                }
                Log.e("TAG" , "onActivityResult: 支付结果:" + resultBuilder.toString());
                payResult = resultBuilder.toString();
                //推送交易结果
                String content = "银行卡普通收款成功  ¥" + dataBinding.generalCount.getText().toString() + " " + getCurrentTime();
                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "尚瀚支付推送提醒", content, () -> {

                });
                break;
            case Activity.RESULT_CANCELED:
                success = false;
                String reason = data.getStringExtra("reason");
                Toast.makeText(GeneralActivity.this, reason, Toast.LENGTH_SHORT).show();

                StringBuilder failBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    failBuilder.append(str);

                }
                payResult = failBuilder.toString();
                break;

        }
        Log.e("TAG", "onActivityResult:payResult :普通收款交易信息:=============" + payResult);

        //上传交易结果


        //回调上传交易结果
        boolean finalSuccess = success;
        bankViewModel.uploadTradeInfo(payResult, () -> {
            if (finalSuccess) {//如果交易成功再跳转
                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", bankViewModel.bankBean.get().getOut_trade_no());
                intent.putExtra("needPrint", true);
                startActivity(intent);

            }
            Log.d(TAG, "bankPay: 上传交易信息成功!");
        });

    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission(int code) {
        permissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {

            if (permission.granted) {
                scanCode(code);
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(GeneralActivity.this, "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).show();

            } else {
                Uri packageURI = Uri.parse("package:" + GeneralActivity.this.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);

            }
        });


    }

    //开始扫描二维码
    private void scanCode(int code) {
        Intent scanIntent = new Intent(GeneralActivity.this, ScanActivity.class);
        startActivityForResult(scanIntent, code);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        zoloz.zolozUninstall();
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37328546/article/details/85776338