支付网关集成时出现 SSLException
Posted
技术标签:
【中文标题】支付网关集成时出现 SSLException【英文标题】:Getting SSLException while payment gateway integration 【发布时间】:2018-12-05 03:03:05 【问题描述】:我只是集成了 Frimi 支付网关。第一步是尝试生成访问令牌,生成令牌后将调用支付链接。 但是出现错误:- 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:
// 在这里我发布了我想要生成访问令牌的完整代码。 /please help..help 将不胜感激
【问题讨论】:
你能给我们看看堆栈跟踪吗 我刚刚附加了一个图像文件...无论 logcat 中的值是什么 【参考方案1】://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;
【讨论】:
【参考方案2】:您没有以正确的方式构建呼叫,这就是您应该这样做的方式。
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 操作系统版本。如果您使用的是 WiFi,请考虑改用您的移动网络。
进一步编辑:
我看到您运行的是 4.4.2 版本,请尝试运行操作系统版本为 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 证书显然有问题。尝试让您的服务器管理员提供帮助。
【讨论】:
以上是关于支付网关集成时出现 SSLException的主要内容,如果未能解决你的问题,请参考以下文章
Ingenico .net SDK 集成 - 进行任何 API 调用时出现未经授权和连接关闭异常
在 ionic android 移动应用程序中集成 ccavenue 支付网关