Android 微信与支付宝WebView支付调起

先上效果图:

现在越来越多的WebView唤起支付了,今天做个总结记录一下自己BUG;

官方文档讲的很详细;

首先接入sdk 

放到libs包里

在build.gradle

repositories {
    flatDir {
        dirs 'libs'
    }
}
implementation files('libs/alipaySdk-15.7.7-20200702160044.aar')

按上面的方法成功接入SDK 微信与支付宝接入方法一样

接下来就调起支付了:

PAY_URLS=是调起地址

tradenum=是订单信息 

String url = PAY_URLS + "?tradenum=" + tradenum;
调起支付
webView.loadUrl(url);//

对接下来的请求监听

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    try {
        if (url.startsWith("weixin://") || url.startsWith("alipays://")) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            mActivity.startActivity(intent);
            return true;
        }
    } catch (Exception e) {
        return false;
    }

    if (url.contains("https://wx.tenpay.com")) {
        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Referer", referer);// referer=是你们公司注册的域名网址(微信的需要)
        view.loadUrl(url, extraHeaders);
        referer = url;
        return true;
    }
    view.loadUrl(url);
    return true;
}

到这就完成支付了

完整代码

PayDialog extends Dialog {
    private static final String DEFAULT_REFERER = "https://wxapp.kuaipantech.com";
    private String PAY_URLS = "https://wxapp.kuaipantech.com/h5demo/wxjspay/weixin_to_h5.php";

    public interface ICallback {
        void onResult(int ret, String msg);
    }

    private static final String TAG = "AlertDialog";
    private Activity mActivity;

    private ProgressBar mProBar;
    private WebView webView;
    private PayDialog.ICallback mCallback;
    private Button confirm_the_payment;//确认支付
    //    private String tradenum = "kp_27_20200627152653_407742";
    private int payState = 0;
    public String guid = "";
    public String productcode = "";
    public String cp_orderid = "";
    public String globaluserid = "";
    public String globalusername = "";
    public String cotype = "lianyun";
    private boolean choose = true;
    private MyRadioButton mWeChat_id, mtreasure_id;

    public void setCallback(PayDialog.ICallback callback) {
        mCallback = callback;
    }

    public PayDialog(Activity context) {
        super(context, R.style.MyTheme_CustomDialog_LoginDialog);
        this.mActivity = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_dialog);
        setCanceledOnTouchOutside(false);

        mProBar = findViewById(R.id.progressBar1);

        findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
                if (mCallback != null) {
                    mCallback.onResult(1, "");
                }
            }
        });
        mWeChat_id = findViewById(R.id.mWeChat_id);
        mtreasure_id = findViewById(R.id.treasure_id);
        mWeChat_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                choose = isChecked;
            }
        });
//        调起支付
        confirm_the_payment = findViewById(R.id.confirm_the_payment);
        confirm_the_payment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (choose) {
                    //微信
                    PAY_URLS = "https://wxapp.kuaipantech.com/h5demo/wxjspay/weixin_to_h5.php";
                    weChatpay();
                } else {
                    //支付宝
                    PAY_URLS = "https://kppay.kuaipantech.com/alipay_wap/wappay/pay.php";
                    weChatpay();
                }
            }
        });

//        String url = PAY_URL + "?tradenum=" + tradenum;
        webView = findViewById(R.id.webview);
//        webView.loadUrl(url);
        initView();

    }



    private void weChatpay() {
        if (payState == 0) {
//                    String url = PAY_URL + "?tradenum=" + tradenum;
//                    webView.loadUrl(url);
            //处理按钮
            confirm_the_payment.setText("生成订单...");
            confirm_the_payment.setEnabled(false);
            payState = 1;

            //生成订单
            HashMap<String, String> map = new HashMap();
            map.put("productcode", productcode);
            map.put("cp_orderid", cp_orderid);
            map.put("guid", guid);
            map.put("globaluserid", globaluserid);
            map.put("globalusername", globalusername);
            map.put("cotype", cotype);
            new RequestPayTask(new RequestPayTask.ICallback() {
                @Override
                public void onResult(HashMap<String, String> map) {
                    //获取订单号
                    String msg = "";
                    int code = 0;
                    if (map == null) {
                        msg = "map null";
                    } else if (map.containsKey("tradenum")) {
                        code = 1;
                        String tradenum = map.get("tradenum");

                        //调用微信
                        confirm_the_payment.setText("支付中,请稍等...");
                        confirm_the_payment.setEnabled(false);
                        payState = 2;

                        String url = PAY_URLS + "?tradenum=" + tradenum;
                        webView.loadUrl(url);

                    } else {
                        if (map.containsKey("error")) {
                            msg = map.get("error");
                        } else {
                            msg = "error";
                        }
                        Toast.makeText(mActivity, msg, Toast.LENGTH_LONG).show();
                        confirm_the_payment.setEnabled(true);
                        confirm_the_payment.setText("生成订单失败,点击重试");
                        payState = 0;
                    }
                }
            }).execute(map);

        } else if (payState == 2) {
            dismiss();
            if (mCallback != null) {
                mCallback.onResult(1, "");
            }
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && payState == 2) {
            confirm_the_payment.setText("支付完成");
            confirm_the_payment.setEnabled(true);
        }
    }

    private void initView() {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //设置自适应屏幕,两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //webView.addJavascriptInterface(new JsObject(), "client");
        webView.addJavascriptInterface(new PayDialog.JavascriptCallback(), "android");
        webView.clearCache(true);
        //复写shouldOverrideUrlLoading()方法,使得打开网页时不调用系统浏览器, 而是在本WebView中显示
        webView.setWebViewClient(new WebViewClient() {
            String referer = DEFAULT_REFERER;

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    if (url.startsWith("weixin://") || url.startsWith("alipays://")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        mActivity.startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }

                if (url.contains("https://wx.tenpay.com")) {
                    Map<String, String> extraHeaders = new HashMap<>();
                    extraHeaders.put("Referer", referer);
                    view.loadUrl(url, extraHeaders);
                    referer = url;
                    return true;
                }
                view.loadUrl(url);
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根

                if (newProgress == 100) {
                    mProBar.setVisibility(View.INVISIBLE);//加载完网页进度条消失
                } else {
                    mProBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    mProBar.setProgress(newProgress);//设置进度值
                }

            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b2 = new AlertDialog.Builder(mActivity)
                        .setTitle("提示").setMessage(message)
                        .setPositiveButton("ok",
                                new AlertDialog.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();
                                    }
                                });

                b2.setCancelable(false);
                b2.create();
                b2.show();
                return true;
            }
        });
    }

    class JavascriptCallback {
        @JavascriptInterface
        public void paySuccess(String token, String phone, String guid) {
        }
    }

}
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="260dp"
    android:layout_height="285dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:background="@drawable/dialog_bg"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="10dp">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageButton
            android:id="@+id/close"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_gravity="right"
            android:background="@android:color/transparent"
            android:src="@mipmap/down_notify_close" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:lineHeight="20dp"
            android:text="温馨提示,支付过程会有延时,请不要重复支付!"
            android:textAlignment="center"
            android:textColor="@android:color/black"
            android:textSize="16sp" />

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="200dp"
            android:layout_height="3dip"
            android:layout_marginTop="20dp"
            android:progressDrawable="@drawable/webview_probar_bg"
            android:visibility="invisible" />


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/weChatfigure"
                android:layout_marginTop="10dp"
                android:layout_marginRight="20dp"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/icontest">
            </ImageView>
            <TextView
                android:layout_marginTop="10dp"
                android:layout_toRightOf="@+id/weChatfigure"
                android:text="微信支付"
                android:gravity="center_vertical"
                android:layout_width="match_parent"
                android:layout_height="40dp">

            </TextView>
            <View
                android:layout_below="@+id/weChatfigure"
                android:background="#f5f5f5"
                android:layout_width="match_parent"
                android:layout_height="0.5dp"></View>
            <ImageView
                android:id="@+id/treasure"
               android:layout_below="@+id/weChatfigure"
                android:layout_marginTop="1dp"
                android:layout_marginRight="20dp"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/alipay">
            </ImageView>
            <TextView

                android:layout_toRightOf="@+id/treasure"
                android:layout_alignTop="@+id/treasure"
                android:text="支付宝支付"
                android:gravity="center_vertical"
                android:layout_width="match_parent"
                android:layout_height="40dp">

            </TextView>

            <RadioGroup

                android:layout_alignTop="@+id/weChatfigure"
                android:layout_width="30dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                >

                <kptech.game.kit.view.MyRadioButton
                    android:layout_marginTop="5dp"
                    android:id="@+id/mWeChat_id"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:checked="true"
                    android:gravity="center"
                    app:drawableHeight="30dp"
                    app:drawableLeft="@drawable/selector_radio"
                    app:drawableWidth="30dp" />

                <kptech.game.kit.view.MyRadioButton
                    android:layout_marginTop="10dp"
                    android:id="@+id/treasure_id"
                    android:layout_width="30dp"
                    android:layout_height="30dp"

                    android:drawablePadding="5dp"
                    android:gravity="center"
                    app:drawableHeight="30dp"
                    app:drawableLeft="@drawable/selector_radio"
                    app:drawableWidth="30dp" />
            </RadioGroup>
            <Button
                android:id="@+id/confirm_the_payment"
                android:layout_below="@+id/treasure"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="20dp"
                android:layout_marginLeft="20dp"
                android:layout_weight="1"
                android:gravity="center"
                android:background="@drawable/mpaytreasure"
                android:text="确认支付"
                android:textColor="#ffffff"
                android:textSize="16sp" />
        </RelativeLayout>
    </LinearLayout>


</FrameLayout>

希望对您有帮助

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值