1

我在我的应用程序中集成了自定义浏览器以进行 PayU 集成。我没有向 PayU URL ( https://secure.payu.in/_payment ) 发送任何参数。我正在服务器端执行此操作(向 PayU 发送参数)。我只需要自定义浏览器,这就是我使用这个的原因。这对我来说很好,但付款成功后它显示空白屏幕。在这个白色的空白屏幕之后如何导航到我的应用程序。

如何获取自定义浏览器的 URL?

参考链接:https ://github.com/payu-intrepos/Android-Custom-Browser/wiki/v5.2.2

依赖:

compile 'com.payu.custombrowser:payu-custom-browser:5.2.2'

代码:

自定义浏览器XL:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/r_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">
    <FrameLayout
        android:id="@+id/parent"
        android:visibility="gone"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:id="@+id/trans_overlay"
        android:layout_height="match_parent"
        android:orientation="horizontal"
       >
    </LinearLayout>
</RelativeLayout>

custombrowser.java

 try {
            Class.forName("com.payu.custombrowser.Bank");
            final Bank bank = new Bank() {
                @Override
                public void registerBroadcast(BroadcastReceiver broadcastReceiver, IntentFilter filter) {
                    mReceiver = broadcastReceiver;
                    registerReceiver(broadcastReceiver, filter);
                }

                @Override
                public void unregisterBroadcast(BroadcastReceiver broadcastReceiver) {
                    if(mReceiver != null){
                        unregisterReceiver(mReceiver);
                        mReceiver = null;
                    }
                }

                @Override
                public void onHelpUnavailable() {
                    findViewById(R.id.parent).setVisibility(View.GONE);
                    findViewById(R.id.trans_overlay).setVisibility(View.GONE);
                }

                @Override
                public void onBankError() {
                    findViewById(R.id.parent).setVisibility(View.GONE);
                    findViewById(R.id.trans_overlay).setVisibility(View.GONE);
                }

                @Override
                public void onHelpAvailable() {
                    findViewById(R.id.parent).setVisibility(View.VISIBLE);
                }

            };
            Bundle args = new Bundle();
            args.putInt("webView", R.id.webview);
            args.putInt("tranLayout",R.id.trans_overlay);
            args.putInt("mainLayout",R.id.r_layout);
            args.putBoolean("showCustom", true);
            bank.setArguments(args);
            findViewById(R.id.parent).bringToFront();
            try {
                getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.cb_fade_in, R.anim.cb_face_out).add(R.id.parent, bank).commit();
            }catch(Exception e)
            {
                e.printStackTrace();
                finish();
            }

            webView.setWebChromeClient(new PayUWebChromeClient(bank));
            webView.setWebViewClient(new PayUWebViewClient(bank));
        } catch (ClassNotFoundException e) {
            webView.getSettings().setSupportMultipleWindows(true);
            webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void onSuccess() {

                    onSuccess("");
                }

                @JavascriptInterface
                public void onSuccess(final String result) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.putExtra("result", result);
                            setResult(RESULT_OK, intent);
                            finish();

                        }
//                }
                    });
                }

                @JavascriptInterface
                public void onFailure() {
                    onFailure("");
                }

                @JavascriptInterface
                public void onFailure(final String result) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.putExtra("result", result);
                            setResult(RESULT_CANCELED, intent);
                            finish();
                        }
                    });
                }
            }, "PayU");

            webView.setWebChromeClient(new WebChromeClient() {

            });
            webView.setWebViewClient(new WebViewClient());
        }

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);

     String   PostData="UserUniqueID=" + UUUID + "&OrderID=" + orderid + "&PFID=" + pid + "&ReloadCash=" + reloadcash + "&DeviceID=" + DEVICEID ;

        webView.postUrl(WebUrl.Bankurl, PostData.getBytes());
      //Weburl.posturl is my server side bank url.
    }


    @Override
    public void onBackPressed(){
        boolean disableBack = false;
        if(cancelTransaction){
            cancelTransaction = false;
            Intent intent = new Intent();
            intent.putExtra("result", "Transaction canceled due to back pressed!");
            setResult(RESULT_CANCELED, intent);
            super.onBackPressed();
            return;
        }
        try {
            Log.v("TAG_PAUSEURLL", "" + "PAUSEURL");
            Bundle bundle = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA).metaData;
            disableBack = bundle.containsKey("payu_disable_back") && bundle.getBoolean("payu_disable_back");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if(!disableBack) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setCancelable(false);
            alertDialog.setMessage("Do you really want to cancel the transaction ?");
            alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelTransaction = true;
                    dialog.dismiss();
                    onBackPressed();
                }
            });
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
    }

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

        webView.clearCache(true);
        webView.clearHistory();
        webView.destroy();
    }
4

1 回答 1

0

喜欢这个代码

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


    btnBuy.setOnClickListener(new OnClickListener() {

        @SuppressLint({ "SetJavaScriptEnabled", "ShowToast" }) @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(f_nm && f_pn  && f_email )
            {
                webview.setVisibility(View.VISIBLE);
                Integer randomNum = randInt(0, 9999999);
                txnid=randomNum.toString();
                firstname=etName.getText().toString();
                email=etEmail.getText().toString();
                amount=study_material_price;
                productinfo=study_material_name;
                phone=etPhone.getText().toString();
                String hashSequence = merchant_key+"|"+txnid+"|"+amount+"|"+productinfo+"|"+firstname+"|"+email+"|||||||||||"+salt;
                hash = hashCal("SHA-512", hashSequence);
                webview.addJavascriptInterface(new PayUJavaScriptInterface(), "PayUMoney");
                String json ="txnid="+txnid+"&key="+merchant_key+"&amount="+amount+"&hash="+hash+"&productinfo="+productinfo+"&surl="+SURL+"&furl="+FURL+"&firstname="+firstname+"&email="+email+"&phone="+phone+"&service_provider=payu_paisa";
                webview.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
                webview.getSettings().setDomStorageEnabled(true);
                webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setSupportMultipleWindows(true);
                webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                webview.getSettings().setSupportZoom(true);       //Zoom Control on web (You don't need this
                //if ROM supports Multi-Touch
                webview.getSettings().setBuiltInZoomControls(true);
                webview.setWebViewClient(new WebViewClient());
                webview.setWebViewClient(
                        new SSLTolerentWebViewClient()
                        );
                webview.postUrl("https://secure.payu.in/_payment", EncodingUtils.getBytes(json, "BASE64"));

                try {

                    webview.setWebViewClient(new WebViewClient() {
                        @Override
                        public void onReceivedError(WebView view, int errorCode,
                                String description, String failingUrl) {
                            Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
                        }

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            // handle different requests for different type of files
                            // this example handles downloads requests for .apk and .mp3 files
                            // everything else the webview can handle normally
                            if (url.endsWith(".mp3")||url.endsWith(".zip") || url.endsWith(".pdf") || url.endsWith(".jpg")|| url.endsWith(".doc")|| url.endsWith(".png")|| url.endsWith(".docx")|| url.endsWith(".xml")|| url.endsWith(".gif")) {
                                String urlSplit[] = url.split("/");
                                String fileName = urlSplit[urlSplit.length-1];
                                Uri source = Uri.parse(url);
                                // Make a new request pointing to the .apk url
                                DownloadManager.Request request = new DownloadManager.Request(source);
                                // appears the same in Notification bar while downloading
                                request.setDescription("Description for the DownloadManager Bar");
                                request.setTitle(fileName);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                }
                                // save the file in the "Downloads" folder of SDCARD
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
                                // get download service and enqueue file
                                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.enqueue(request);
                            }
                            // if there is a link to anything else than .apk or .mp3 load the URL in the webview
                            else view.loadUrl(url);
                            return true;                
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                Toast.makeText(getApplicationContext(), "Please fill all the fields.", 1000).show();
            }
        }
    });
}   

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode)
        {
        case KeyEvent.KEYCODE_BACK:
            if(webview.canGoBack()){
                webview.goBack();
            }else{
                finish();
            }
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

private final class PayUJavaScriptInterface {
    PayUJavaScriptInterface() {
    }

    /**
     * This is not called on the UI thread. Post a runnable to invoke
     * loadUrl on the UI thread.
     */
    @JavascriptInterface
    public void success(long id, final String pId) {
        mHandler.post(new Runnable() {
            public void run() {
                mHandler = null;
                Toast.makeText(getApplicationContext(), "Your Transaction is Successful", 1000).show();
                status="Success";
                paymentId=pId;
                new StoreTransactionData().execute();
                Intent intent = new Intent();
                intent.putExtra("status", "success");
                intent.putExtra("transaction_id", paymentId);
                setResult(RESULT_OK, intent);
                studyDownloadPaid();
                finish();
            }
        });
    }



    @JavascriptInterface
    public void failure(final String id, String error) {
        Log.d("transaction data fail id", id +"   " +study_material_name);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                paymentId=id;
                status="Faluire";
                new StoreTransactionData().execute();
                cancelPayment();
            }
        });
    }

    @JavascriptInterface
    public void failure() {
        failure("");
    }

    @JavascriptInterface
    public void failure(final String params) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                paymentId=params;
                status="Faluire";
                new StoreTransactionData().execute();
                Log.d("transaction data fail param", params);
                Intent intent = new Intent();
                intent.putExtra("status", params);
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        });
    }

}

private void cancelPayment() {
    Intent intent = new Intent();
    intent.putExtra("status", "cancel");
    //mWebView.destroy();
    setResult(RESULT_CANCELED, intent);
    finish();
}

public static String hashCal(String type, String str) {
    byte[] hashseq = str.getBytes();
    StringBuffer hexString = new StringBuffer();
    try {
        MessageDigest algorithm = MessageDigest.getInstance(type);
        algorithm.reset();
        algorithm.update(hashseq);
        byte messageDigest[] = algorithm.digest();
        for (int i = 0; i < messageDigest.length; i++) {
            String hex = Integer.toHexString(0xFF & messageDigest[i]);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex);
        }
    } catch (NoSuchAlgorithmException nsae) {
    }
    return hexString.toString();
}

public static int randInt(int min, int max) {
    // Usually this should be a field rather than a method variable so
    // that it is not re-seeded every call.
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}


private class SSLTolerentWebViewClient extends WebViewClient {

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed(); // Ignore SSL certificate errors
    }

}
于 2015-10-14T12:18:12.927 回答