ApplePay对接java后台详细代码

java代码
ios端支付完成后,调用此接口

@Controller
@RequestMapping("user/applepay")
@Api(value="ApplePayController",description="苹果支付")
public class ApplePayController {
	// 购买凭证验证地址
	private static final String verifyReceiptUrl = "https://buy.itunes.apple.com/verifyReceipt";
	// 测试的购买凭证验证地址
	private static final String verifyReceiptUrlSandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
	
	private static int requestCounts = 0;

	/**
	 * 重写X509TrustManager
	 */
	private static TrustManager myX509TrustManager = new X509TrustManager() {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	};
	
	@Autowired
	private IOrderService orderService;

	/**
	 * 接收iOS端发过来的购买凭证
	 * 
	 * @param url
	 * @param strings
	 * @return
	 */
	@ApiOperation(value="接收iOS端发过来的购买凭证",httpMethod="POST",notes="接收iOS端发过来的购买凭证",produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value="/iap", method = RequestMethod.POST)
	@ResponseBody
	private JsonResult sendHttpsCoon(@ApiParam(value="appBasicParam") AppBasicParam appBasicParam,
			@ApiParam(value="购买凭证", required = true) @RequestParam(value="receipt", required=true)String receipt,
			@ApiParam(value="线上环境true;sanbox环境false", required = false) @RequestParam(value="chooseEnv", required=true)Boolean chooseEnv) {
		if ( null == receipt ) {
			return super.renderParamsError();
		} else {
			String url = chooseEnv ? verifyReceiptUrl : verifyReceiptUrlSandbox;
			Long uid = Long.valueOf(appBasicParam.getUid());
			try {
				// 设置SSLContext
				SSLContext ssl = SSLContext.getInstance("SSL");
				ssl.init(null, new TrustManager[] { myX509TrustManager }, null);

				// 打开连接
				HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
				// 设置套接工厂
				conn.setSSLSocketFactory(ssl.getSocketFactory());
				// 加入数据
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-type", "application/json");
				conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
//				conn.setDoInput(true);
				conn.setDoOutput(true);
				JSONObject obj = new JSONObject();
				obj.put("receipt-data", receipt);
				// 获取输出流
				BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
				buffOutStr.write(obj.toString().getBytes());
				buffOutStr.flush();
				buffOutStr.close();
				// 获取输入流
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				//苹果返回的string
				String stringadsf = sb.toString();
				conn.getInputStream().close();

				JSONObject job = JSONObject.parseObject(stringadsf);// App Store的返回值
				if (job.getString("status").equals("0")) {
					// 跟苹果验证有返回结果--验证成功
					JSONObject code = JSONObject.parseObject(job.getString("receipt"));
					String creation_date_ms = code.getString("receipt_creation_date_ms"); // receipt创建日期(ms)
					JSONArray jsonArray = (JSONArray) code.get("in_app");// 订单列表
					JSONObject targetOrder = null;
					if (1 == jsonArray.size()) {
						// 订单列表为一个,直接取出
						targetOrder = jsonArray.getJSONObject(0);
					} else{
						// 订单列表为多个,根据支付订单创建时间戳获取本次订单 
						Log4jUtil.CommonLog.error("苹果--->订单列表为多个 " );
						for (int i = 0; i < jsonArray.size(); i++) {
							JSONObject orderItem = jsonArray.getJSONObject(i);
							if (orderItem.getString("purchase_date_ms").equals(creation_date_ms)) {
								targetOrder = orderItem;
							}
						}
					}
					if (null == targetOrder) {
						Log4jUtil.CommonLog.error("验证结果中不存在订单信息 " );
						return super.renderError("验证结果中不存在订单信息-1");
					} else {
						//获取apple_product_id
						String product_id = targetOrder.getString("product_id");
						// String money = product_id.substring(4, product_id.length());
						String transaction_id = targetOrder.getString("transaction_id");// transaction_id交易号
						//将凭证解析出的购买信息和本地服务端作对比
						//更新order数据库
						String price = "0";
						String goodsName = "商品名称";
						if(product_id.equals(VIPConstant.VIP_NORMAL_PRO_ID)) {
							price = VIPConstant.VIP_NORMAL_RMB;
							goodsName = VIPTypeStatus.NORMAL.getName();
						} else if(product_id.equals(VIPConstant.VIP_SILVER_PRO_ID)) {
							price = VIPConstant.VIP_SILVER_RMB;
							goodsName = VIPTypeStatus.SILVER.getName();
						} else if(product_id.equals(VIPConstant.VIP_GOLD_PRO_ID)) {
							price = VIPConstant.VIP_GOLD_RMB;
							goodsName = VIPTypeStatus.GOLD.getName();
						} else if(product_id.equals(VIPConstant.VIP_SUPER_PRO_ID)) {
							price = VIPConstant.VIP_SUPER_RMB;
							goodsName = VIPTypeStatus.SUPER.getName();
						}else {
							return super.renderError("根据productId,查询app本地商品失败-1", 500);
						}
						
						OrderBean bean = new OrderBean();
						bean.setUserId(uid);
						bean.setRealFee(new BigDecimal(price));
						bean.setTotalProductFee(new BigDecimal(price));
						bean.setGoodsName(goodsName);
						bean.setPayType((byte) 1);//表示ApplePay
						bean.setCode(transaction_id);
						requestCounts = 0;
						return orderService.addAndFinishOrder(bean);
					}
					
				} else if (job.getString("status").equals("21007")) {
					Log4jUtil.CommonLog.error("21007: 收据信息是测试用(sandbox),但却被发送到正式环境中验证 " );
					return super.renderError("21007验证支付信息失败-1", 500);
				}  else if (job.getString("status").equals("21008") && requestCounts < 5) {
					Log4jUtil.CommonLog.error("21008 receipt是生产receipt,但却发送至Sandbox环境的验证服务 " );
					requestCounts ++;
					// 重新请求服务器,requestCounts 计数,使用生产环境的url验证地址(基于ios端无法判断传入 chooseEnv参数)
					return sendHttpsCoon(appBasicParam, receipt, true);
					
					
					//return super.renderError("21008验证支付信息失败-1", 500);
				} else {
					Log4jUtil.CommonLog.error("苹果没有返回的验证信息 " );
					return super.renderError("验证支付信息失败-2", 500);
				}
			} catch (Exception e) {
				Log4jUtil.CommonLog.error("苹果返回验证信息 " );
				return super.renderError("验证支付信息失败-3", 500);
			}
		}
	}
	}

猜你喜欢

转载自blog.csdn.net/gentlu/article/details/84023302
今日推荐