流程:支付由IOS端发起支付,java后台只做支付凭证校验
//苹果官网支付结果验证地址
private String url = "https://buy.itunes.apple.com/verifyReceipt";
//苹果官网支付结果验证地址(测试地址)
private String testUrl = "https://sandbox.itunes.apple.com/verifyReceipt";
IOS支付完后会把支付凭证传到后台来,后台通过支付凭证进行支付结果校验
/**
* 获取支付结果
* mapJsonStr 支付凭证
*/
@SuppressWarnings("unchecked")
public Map<String, String> getPayResult(String mapJsonStr){
if(mapJsonStr == null){
return null; //支付凭证为空
}
Map<String, String> resultDataMap = null;
try{
//根据支付凭证到官网查询支付结果
String payResultStr = processPayment(url, mapJsonStr);
if (payResultStr == null) {
//数据异常,请稍后重试
return null;
}
//解析苹果支付返回的参数信息
Map<String, Object> payResultMap = JSON.parseObject(payResultStr, Map.class);
log.info("解析苹果支付返回的参数信息 : " + payResultMap);
Integer status = (Integer)payResultMap.get("status");//只有status ==0才是支付成功
log.info("苹果支付返回状态 : " + status);
if(null != status && status == 21007){
//沙盒测试,调用沙盒测试地址去解析
payResultStr = processPayment(testUrl, mapJsonStr);
if (payResultStr == null) {
//数据异常,请稍后重试
return null;
}
//解析苹果支付返回的参数信息
payResultMap = JSON.parseObject(payResultStr, Map.class);
status = (Integer)payResultMap.get("status");//只有status ==0才是支付成功
}
if(null != status && status == 0){
//支付成功
//获取返回的信息
String receipt = payResultMap.get("receipt") + "";
if(payResultStr != null){
resultDataMap = JSON.parseObject(receipt, Map.class);
}
}
}catch(Exception e){
e.printStackTrace();
log.error("getPayResult()"+e.getMessage());
}
return resultDataMap;
}
/**
* 根据支付凭证到官网查询支付结果
* @param url
* @param receipt
* @return
* @throws SystemException
*/
public String processPayment(String url, String receipt)
throws SystemException {
String result = "";
OutputStreamWriter outputStreamWriter = null;
BufferedReader reader = null;
try {
URL urlcon = new URL(url);
HttpURLConnection conn = (HttpsURLConnection) urlcon.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
outputStreamWriter = new OutputStreamWriter(conn.getOutputStream());
outputStreamWriter.write(receipt);
outputStreamWriter.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String temp = reader.readLine();
while (temp != null) {
if (result != null){
result += temp;
}else{
result = temp;
}
temp = reader.readLine();
}
}catch (ProtocolException e3) {
e3.printStackTrace();
}catch (MalformedURLException e2) {
e2.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(null != outputStreamWriter){
outputStreamWriter.close();
}
if(null != reader){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}