1. 程式人生 > >Android 微信/支付寶 h5調原生支付

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()
    }


}