Android 微信/支付宝 h5调原生支付

记录一下Android的支付h5调原生支付

流程是客户端通过后台的接口生成支付订单,后台生成订单后会返回一个h5的支付url

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.CountDownTimer
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast

/**
 * 移动支付 h5 调用原生支付(微信/支付宝)
 * Created by ZYB on 2018/9/5 0005.
 */
object PaymentUtil {
    fun pay(context: Context, payurl: String) {


        //如果10s内没收到shouldOverrideUrlLoading的回调,则重新调用
        //我遇到的情况是在红米note4x调用支付宝 第一次会连shouldOverrideUrlLoading都不会回调,第二次就行
        val countDownTimer = object : CountDownTimer(10000, 1000) {
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                pay(context, payurl)
            }
        }

        var webview = WebView(context)
        webview.settings.javaScriptEnabled = true;
        webview.settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        webview.settings.setJavaScriptEnabled(true)
        webview.settings.setSavePassword(false)
        webview.settings.setJavaScriptCanOpenWindowsAutomatically(true)
        webview.settings.setMinimumFontSize(webview.settings.getMinimumFontSize() + 8)
        webview.settings.setAllowFileAccess(false)
        webview.settings.setTextSize(WebSettings.TextSize.NORMAL)
        webview.setVerticalScrollbarOverlay(true)
        webview!!.setWebViewClient(object : WebViewClient() {

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                //判断是否是微信支付还是支付宝支付
                if (url!!.startsWith("weixin://wap/pay?")) {
                    try {
                        countDownTimer.cancel()
                        var intent = Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        context.startActivity(intent);
                    } catch (e: Exception) {
                        Toast.makeText(context, "设备缺少微信应用,支付失败", Toast.LENGTH_SHORT).show();
                    }
                } else if (url!!.contains("platformapi/startApp")) {
                    try {
                        countDownTimer.cancel()
                        val intent = Intent()
                        intent.action = Intent.ACTION_VIEW
                        intent.data = Uri.parse(url)
                        intent.addCategory("android.intent.category.BROWSABLE")
                        intent.component = null
                        context.startActivity(intent)
                    } catch (e: Exception) {
                        Toast.makeText(context, "设备未安装支付宝", Toast.LENGTH_SHORT).show()
                    }

                }
                return super.shouldOverrideUrlLoading(view, url)
            }
        })
        webview!!.loadUrl(payurl)
        countDownTimer.start()
    }


}

 

展开阅读全文

没有更多推荐了,返回首页