支付网关集成时获取 SSLException

Getting SSLException while payment gateway integration

我正在集成 Frimi 支付网关。第一步是尝试生成访问令牌,生成令牌后将调用支付 link。 但是我收到错误:- SSLException: Connection closed by peer.

 public  void TokenGenerationProcess() {
        class WaitingforResponse extends AsyncTask<Void, Void, String> {
            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                //  progressDialog = ProgressDialog.show(getActivity().getBaseContext(), "Waiting for Token Generation...", "Please Wait...", false, false);
            }

            @Override
            protected String doInBackground(Void... params) {
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .build();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

                String json = "";
                RequestBody body = RequestBody.create(mediaType, json);
               /* https://ideabiz?grant_type=password&username=99R_User&password=99R_User&scope=SANDBOX

                https://igrant_type=refresh_token&refresh_token="+Message+"&scope=SANDBOX */
                // Message="d6a5be5f5455c87c21442ba3d5201c8c";
                Request request = new Request.Builder()
                        .url("https://uatapi.nationstrust.com:8243/token?grant_type=client_credentials")

                        .addHeader("content-type", "application/x-www-form-urlencoded")
                        .addHeader("authorization", "Basic N000SDNmU3RtVERuZmZ1R0JNMlBGR1FXdmtFYTpEQUFJcEprVUhjdXBwcEx4dkRPSkFYZjNwMmth")
                        .post(body)
                        .build();
//Bearer aUFVMWFRd2Vpb2txQUI2VTFkajBFZWRkTTBZYTpEMzZfbU9GM2ZlYkFEaWRiMGp0ZUZCN2xGUUlh")


                try {
                    okhttp3.Response response = client.newCall(request).execute();
                    String test = response.body().string();
                    if (response.isSuccessful()) {
                       /* int  success = response.code();

                        Headers responseHeaders = response.headers();
                        for (int i = 0; i < responseHeaders.size(); i++) {

                            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                        }

                        System.out.println(test);
                        ///   {"scope":"default","token_type":"bearer","expires_in":3600,"refresh_token":"2d23c431f25e10e5abcd16bea931d0a","access_token":"b0bffddb2be384c53135cadf0f565c2"}
                        try {
                            JSONObject jsonObject = new JSONObject(test);
                            Log.e(" scope", "" + jsonObject.get("scope"));
                            Log.e(" token_type", "" + jsonObject.get("token_type"));
                            Log.e(" expires_in", "" + jsonObject.get("expires_in"));
                            Log.e(" refresh_token", "" + jsonObject.get("refresh_token"));
                            Log.e(" access_token", "" + jsonObject.get("access_token"));
                            // Message = (String) jsonObject.get("refresh_token");

                            String  access_token = (String) jsonObject.get("access_token");
                            String  refresh_token = (String) jsonObject.get("refresh_token");
                            PersistenceManager.saveRefreshToken(getApplicationContext(), refresh_token);
                            PersistenceManager.saveSessionId(getApplicationContext(), access_token);
                            PersistenceManager.saveTime(getApplicationContext(), String.valueOf(System.currentTimeMillis()));
     */                       // reference= (String) jsonObject.get("Refno");

                    } else {
                        System.out.println(test);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                // progressDialog.dismiss();
            }


        }
        WaitingforResponse WaitingforResponse = new WaitingforResponse();
        WaitingforResponse.execute();

    }

请参阅下面的 Stacktrace:

// 在这里,我发布了我试图生成访问令牌的完整代码。 /请帮助..帮助将不胜感激

你没有以正确的方式建立调用,这才是你应该做的。

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
    RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials");
    Request request = new Request.Builder()
            .url("https://uatapi.nationstrust.com:8243/token")
            .post(body)
            .addHeader("content-type", "application/x-www-form-urlencoded")
            .addHeader("authorization", "Basic N000SDNmU3RtVERuZmZ1R0JNMlBGR1FXdmtFYTpEQUFJcEprVUhjdXBwcEx4dkRPSkFYZjNwMmth")
            .build();

    try {
        Response response = client.newCall(request).execute();
        String test = response.body().string();
        if (response.isSuccessful()) {
            System.out.println(test);
        } else {
            System.out.println(response.code() +" : "+ response.message());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

您的 JSON 回复将如下所示:

{
"access_token": "7389a302-82f9-3fa9-b7a3-fefa45d2de32",
"scope": "am_application_scope default",
"token_type": "Bearer",
"expires_in": 500
}

编辑:

然而,这并不能解释为什么您会收到 ssl 异常。我需要更多信息才能弄清楚。 Android OS 版本是您 运行 正在使用您的应用程序的设备。如果您使用的是 WiFi,请考虑改用您的移动网络。

进一步编辑:

我看到你运行正在使用 4.4.2 版尝试 运行 具有 OS 5.1 版以上的设备。你会发现问题可能会消失。如果这没有什么不同,请尝试将此代码添加到您的代码中,确保它在调用之前执行。

public static void initializeSSLContext(Context mContext) {
    try {
        SSLContext.getInstance("TLSv1.2");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        ProviderInstaller.installIfNeeded(mContext.getApplicationContext());
    } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }
}

如果这没有帮助,您的服务器的 ssl 证书显然有问题。尝试让您的服务器管理员协助。

//Please use this it will work 
 OkHttpClient client = null;
                try {
                    client = new OkHttpClient.Builder()
                            .connectTimeout(120, TimeUnit.SECONDS)
                            .writeTimeout(120, TimeUnit.SECONDS)
                            .readTimeout(120, TimeUnit.SECONDS)
                            .sslSocketFactory(new Tls12SocketFactory(), provideX509TrustManager())
                            .build();
                } catch (KeyManagementException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }

//add this method 
  public X509TrustManager provideX509TrustManager() {
        try {
            TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init((KeyStore) null);
            TrustManager[] trustManagers = factory.getTrustManagers();
            return (X509TrustManager) trustManagers[0];
        } catch (NoSuchAlgorithmException | KeyStoreException exception) {
            Log.e(getClass().getSimpleName(), "not trust manager available", exception);
        }

        return null;
    }
//create another java class 

public class Tls12SocketFactory extends SSLSocketFactory {
    private SSLSocketFactory internalSSLSocketFactory;

    public Tls12SocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, null, null);
        internalSSLSocketFactory = context.getSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return internalSSLSocketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return internalSSLSocketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket() throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
    }

    private Socket enableTLSOnSocket(Socket socket) {
        if(socket != null && (socket instanceof SSLSocket)) {
            ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
        }
        return socket;
    }
}