入职新公司后,被安排做支付宝支付服务器端的开发,在阅读了支付宝的开发文档(https://docs.open.alipay.com/54/106370/)后,便开始了开发。
背景:我们公司接入支付宝支付的产品是一款视频剪辑的APP,部分功能需要付费才能解锁,比如去除APP水印等等。支付宝支付接入的需求就是在这个背景下产生的。
流程:
服务器端全部代码如下:
1 @Controller 2 public class ClientAliPayCtrl extends BaseController { 3 4 private Log log = LogFactory.getLog(this.getClass()); 5 //是否打印客户端请求日志 6 private static boolean isParaLog = MyConfigurer.getEvn("request.param.log.open").equals("true")?true:false; 7 @Autowired 8 protected ForbiddenIPService forbiddenIPService; 9 @Autowired 10 private AdChooseService adChooseService; 11 @Autowired 12 private AliPayService alipayService; 13 @Autowired 14 private AsyncInsertService asyncInsertService; 15 @Autowired 16 private ProductService productService; 17 //public AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID, AlipayConfig.RSA2_PRIVATE_KEY,AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE); 18 public static Map<Integer, AlipayClient> alipayClientMap = new HashMap<Integer, AlipayClient>();/** 19 * JAVA服务端SDK生成APP支付订单信息 20 */ 21 @RequestMapping(value="{version}/alipay/preOrder.htm",method={RequestMethod.POST}) 22 void generateOrders(HttpServletRequest request,HttpServletResponse response,@PathVariable(value="version") String version){ 23 Map<String, Object> rMap = new HashMap<String, Object>(); 24 try { 25 Map<String, String> reqPara = this.getReqPara(request, version, false); 26 if(StringUtils.isBlank(reqPara.get("productId"))){ 27 rMap.put("retCode", 0); 28 rMap.put("retMsg", "ERROR:productId is blank"); 29 this.setJsonObject(response, rMap, reqPara); 30 return; 31 } 32 int productId = Integer.valueOf(reqPara.get("productId"));//*****************根据产品id查询产品******************** 33 //SFProduct product = this.alipayService.getProductByProductId(productId); 34 SFProduct product = InitUtil.getProduct(productId); 35 if(product == null){ 36 rMap.put("retCode", 0); 37 rMap.put("retMsg", "Product does not exist"); 38 this.setJsonObject(response, rMap, reqPara); 39 return; 40 } 41 //************************************* 42 String orderId = PayUtil.generateOrderId(productId); 43 MyUtil mu = MyUtil.getInstance(); 44 String ip = PayUtil.ipHandle(reqPara); 45 SFPayOrder payOrder = new SFPayOrder(); 46 payOrder.setPkgType(mu.getPackageTypeMapNew(reqPara.get("pkgName"))); 47 payOrder.setOrderId(orderId);//订单号 48 payOrder.setProductId(productId);//产品ID 49 payOrder.setAppId(product.getAlipayAppId());//APPID 50 payOrder.setOrderTime(mu.getCurrenTime());//订单生成时间 51 payOrder.setImei(reqPara.get("imei")==null?"":reqPara.get("imei"));//用户客户端唯一标识 52 payOrder.setUuId(reqPara.get("uuId")==null?"":reqPara.get("uuId"));//用户客户端唯一标识 53 payOrder.setSpbillCreateIp(ip);//用户IP地址 54 payOrder.setTradeType(AliPayConstant.TRADE_TYPE); 55 payOrder.setPayStatus(-1);//支付状态1.成功,0.失败 56 payOrder.setOrderMsg("OK"); 57 payOrder.setOrderStatus(1); 58 payOrder.setMchId(product.getAlipayPid()); 59 payOrder.setTotalFee(product.getProductPrice()); 60 payOrder.setTimeStamp(System.currentTimeMillis()+""); 61 payOrder.setPayType(2);/**************************调用支付宝接口,生成支付宝订单******************************/ 62 AlipayTradeAppPayRequest alipayTradeAppPayRequest = new AlipayTradeAppPayRequest(); 63 //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 64 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); 65 model.setBody(product.getProductName()); 66 model.setSubject(product.getProductName()); 67 model.setOutTradeNo(orderId); 68 model.setTimeoutExpress("30m"); 69 model.setTotalAmount(PayUtil.f2y(product.getProductPrice())); 70 model.setProductCode("QUICK_MSECURITY_PAY"); 71 alipayTradeAppPayRequest.setBizModel(model); 72 alipayTradeAppPayRequest.setNotifyUrl(MyConfigurer.getEvn("alipay.notifyUrl"));//异步通知地址 73 String orderString = null;try { 74 AlipayClient alipayClient = null; 75 if(alipayClientMap!=null && alipayClientMap.containsKey(productId)){ 76 alipayClient = alipayClientMap.get(productId); 77 } 78 if(alipayClient==null){ 79 alipayClient = new DefaultAlipayClient(AlipayConfig.URL, product.getAlipayAppId(), product.getAlipayPrivateKey(),AlipayConfig.FORMAT, AlipayConfig.CHARSET, product.getAlipayPublicKey(), AlipayConfig.SIGNTYPE); 80 alipayClientMap.put(productId, alipayClient); 81 } 82 AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayClient.sdkExecute(alipayTradeAppPayRequest); 83 orderString = alipayTradeAppPayResponse.getBody();// 就是orderString,可以直接给客户端请求,无需再做处理。 84 } catch (AlipayApiException e) {e.printStackTrace(); 85 rMap.put("retCode", 0); 86 rMap.put("retMsg", e.getMessage()); 87 rMap.put("retMsgCode", e.getErrCode()); 88 this.setJsonObject(response, rMap, reqPara); 89 90 payOrder.setOrderStatus(0); 91 payOrder.setOrderMsg(e.getMessage()); 92 asyncInsertService.addInsertObject(payOrder); 93 return; 94 }/*************************组织响应数据***************************************/ 95 rMap.put("retCode", 1); 96 rMap.put("retMsg", "success"); 97 rMap.put("out_trade_no", orderId); 98 rMap.put("orderString", orderString); 99 this.setJsonObject(response, rMap, reqPara); 100 this.alipayService.saveOrderInfoToLocal(payOrder); 101 } catch (Exception e) { 102 e.printStackTrace(); 103 this.errorAjax(response, e); 104 } 105 }/** 106 * app向服务端请求本次订单支付结果,服务端向支付宝发送请求获取结果,返回给app 107 * @param request 108 * @param response 109 * @param version 110 */ 111 @RequestMapping(value="{version}/alipay/queryOrderStatus.htm",method={RequestMethod.POST}) 112 void queryOrderStatus(HttpServletRequest request,HttpServletResponse response,@PathVariable(value="version") String version){ 113 Map<String,Object> rMap = new HashMap<String, Object>(); 114 try { 115 Map<String, String> reqPara = this.getReqPara(request, version, false); 116 //简单校验String out_trade_no = reqPara.get("out_trade_no"); 117 if(StringUtils.isBlank(out_trade_no)){ 118 rMap.put("retCode", 0); 119 rMap.put("retMsg", "out_trade_no is blank"); 120 this.setJsonObject(response, rMap, reqPara); 121 return; 122 } 123 String trade_no = reqPara.get("trade_no"); 124 int productId = reqPara.get("productId")==null?1001:Integer.valueOf(reqPara.get("productId")); 125 if(productId==0){ 126 productId = 1001; 127 } 128 MyUtil mu = MyUtil.getInstance(); 129 Date cdate = mu.getCurrenTime();//查询数据库订单状态 130 SFPayOrder sfPayOrder = this.alipayService.getSFPayOrderByOrderId(out_trade_no); 131 if(sfPayOrder!= null && sfPayOrder.getPayStatus()!=-1){ 132 rMap.put("retCode", 1); 133 rMap.put("retMsg", sfPayOrder.getPayMsg()); 134 this.setJsonObject(response, rMap, reqPara); 135 sfPayOrder.setQueryStatus(1); 136 sfPayOrder.setQueryTime(cdate); 137 this.asyncInsertService.updateObject(sfPayOrder); 138 return; 139 }//调用接口查询 140 AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest(); 141 AlipayTradeQueryModel model = new AlipayTradeQueryModel(); 142 model.setOutTradeNo(out_trade_no); 143 model.setTradeNo(trade_no); 144 alipayTradeQueryRequest.setBizModel(model); 145 146 SFProduct product = InitUtil.getProduct(productId); 147 if(product == null){ 148 rMap.put("retCode", 0); 149 rMap.put("retMsg", "Product does not exist " + productId); 150 this.setJsonObject(response, rMap, reqPara); 151 return; 152 }AlipayClient alipayClient = null; 153 if(alipayClientMap!=null && alipayClientMap.containsKey(productId)){ 154 alipayClient = alipayClientMap.get(productId); 155 } 156 if(alipayClient==null){ 157 alipayClient = new DefaultAlipayClient(AlipayConfig.URL, product.getAlipayAppId(), product.getAlipayPrivateKey(),AlipayConfig.FORMAT, AlipayConfig.CHARSET, product.getAlipayPublicKey(), AlipayConfig.SIGNTYPE); 158 alipayClientMap.put(productId, alipayClient); 159 } 160 SFPayOrder payOrder = this.alipayService.getSFPayOrderByOrderId(out_trade_no); 161 AlipayTradeQueryResponse alipayTradeQueryResponse; 162 try{ 163 alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest);}catch (Exception e){ 164 if (payOrder != null) { 165 payOrder.setQueryTime(cdate); 166 payOrder.setQueryStatus(2); 167 this.alipayService.updateSFPayOrder(payOrder); 168 } 169 rMap.put("retCode", 0); 170 rMap.put("retMsg", "An error occurred"); 171 this.setJsonObject(response, rMap, reqPara); 172 return; 173 } 174 if (alipayTradeQueryResponse.isSuccess()) {trade_no = alipayTradeQueryResponse.getTradeNo(); 175 String orderStatus = alipayTradeQueryResponse.getTradeStatus(); 176 if("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)){//交易成功 177 rMap.put("retCode", 1); 178 rMap.put("retMsg", orderStatus); 179 this.setJsonObject(response, rMap, reqPara); 180 }else{//交易失败 181 rMap.put("retCode", 0); 182 rMap.put("retMsg", orderStatus); 183 this.setJsonObject(response, rMap, reqPara); 184 }if(payOrder == null){ 185 payOrder = new SFPayOrder(); 186 payOrder.setOrderMsg("OK"); 187 payOrder.setOrderStatus(1); 188 payOrder.setPkgType(mu.getPackageTypeMapNew(reqPara.get("pkgName"))); 189 payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo()); 190 payOrder.setOrderId(out_trade_no); 191 payOrder.setOpenId(alipayTradeQueryResponse.getBuyerUserId()); 192 payOrder.setUserAccount(alipayTradeQueryResponse.getBuyerLogonId()); 193 payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate()); 194 payOrder.setPayStatus(Integer.parseInt(alipayTradeQueryResponse.getTradeStatus())); 195 payOrder.setAppId(product.getAlipayAppId()); 196 payOrder.setPayMsg(orderStatus); 197 payOrder.setPayStatus("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)?1:0); 198 this.alipayService.saveOrderInfoToLocal(payOrder); 199 }else{payOrder.setQueryStatus(1); 200 payOrder.setQueryTime(cdate); 201 payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo()); 202 payOrder.setOpenId(alipayTradeQueryResponse.getBuyerUserId()); 203 payOrder.setUserAccount(alipayTradeQueryResponse.getBuyerLogonId()); 204 payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate()); 205 206 /*交易状态: 207 * WAIT_BUYER_PAY(交易创建,等待买家付款)、 208 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、 209 * TRADE_SUCCESS(交易支付成功)、 210 * TRADE_FINISHED(交易结束,不可退款)*/ 211 payOrder.setPayMsg(orderStatus); 212 payOrder.setPayStatus("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)?1:0); 213 this.alipayService.updateSFPayOrder(payOrder); 214 }} else {rMap.put("retCode", 0); 215 rMap.put("retMsg", alipayTradeQueryResponse.getSubMsg()); 216 this.setJsonObject(response, rMap, reqPara); 217 //交易不存在 218 if ("ACQ.TRADE_NOT_EXIST".equals(alipayTradeQueryResponse.getSubCode())){ 219 if (payOrder != null) { 220 payOrder.setQueryStatus(1); 221 payOrder.setOrderStatus(0); 222 payOrder.setPayStatus(0); 223 payOrder.setQueryTime(cdate); 224 this.alipayService.updateSFPayOrder(payOrder); 225 }}else { 226 if (payOrder != null) { 227 payOrder.setQueryTime(cdate); 228 payOrder.setQueryStatus(2); 229 this.alipayService.updateSFPayOrder(payOrder); 230 } 231 } 232 } 233 } catch (Exception e) { 234 e.printStackTrace(); 235 } 236 }@RequestMapping("/aliPay/updateCheckOrderStatus.htm") 237 public void updateOrderStatus(HttpServletRequest request, HttpServletResponse response) { 238 try { 239 Map<String, String> reqPara = this.getAjaxParas(request); 240 Map<String, Object> rMap = new HashMap<String, Object>(); 241 String out_trade_no = reqPara.get("orderId"); 242 int productId = reqPara.get("productId")==null?1001:Integer.valueOf(reqPara.get("productId")); 243 if(productId==0){ 244 productId = 1001; 245 }MyUtil mu = MyUtil.getInstance(); 246 Date cdate = mu.getCurrenTime(); 247 //查询数据库订单状态 248 SFPayOrder payOrder = this.alipayService.getSFPayOrderByOrderId(out_trade_no); 249 if(payOrder == null){ 250 rMap.put("info","error"); 251 this.setJsonObject(response,rMap); 252 return; 253 } 254 //调用接口查询 255 AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest(); 256 AlipayTradeQueryModel model = new AlipayTradeQueryModel(); 257 model.setOutTradeNo(out_trade_no);//model.setTradeNo(trade_no); 258 alipayTradeQueryRequest.setBizModel(model); 259 260 SFProduct product = InitUtil.getProduct(productId); 261 if(product == null){ 262 rMap.put("info","error"); 263 this.setJsonObject(response,rMap); 264 return; 265 } 266 AlipayClient alipayClient = null; 267 if(alipayClientMap!=null && alipayClientMap.containsKey(productId)){ 268 alipayClient = alipayClientMap.get(productId); 269 }if(alipayClient==null){ 270 alipayClient = new DefaultAlipayClient(AlipayConfig.URL, product.getAlipayAppId(), product.getAlipayPrivateKey(),AlipayConfig.FORMAT, AlipayConfig.CHARSET, product.getAlipayPublicKey(), AlipayConfig.SIGNTYPE); 271 alipayClientMap.put(productId, alipayClient); 272 } 273 // AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest); 274 AlipayTradeQueryResponse alipayTradeQueryResponse; 275 try{ 276 alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest); 277 }catch (Exception e){ 278 if (payOrder != null) { 279 payOrder.setQueryTime(cdate);payOrder.setQueryStatus(2); 280 this.alipayService.updateSFPayOrder(payOrder); 281 } 282 rMap.put("retCode", 0); 283 rMap.put("retMsg", "An error occurred"); 284 this.setJsonObject(response, rMap, reqPara); 285 return; 286 } 287 log.info(alipayTradeQueryResponse.toString());if (alipayTradeQueryResponse.isSuccess()) { 288 String orderStatus = alipayTradeQueryResponse.getTradeStatus(); 289 log.info(orderStatus); 290 payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo()); 291 payOrder.setOpenId(alipayTradeQueryResponse.getBuyerUserId()); 292 payOrder.setUserAccount(alipayTradeQueryResponse.getBuyerLogonId()); 293 payOrder.setPayTime(new Date()); 294 payOrder.setPayMsg(orderStatus); 295 payOrder.setPayStatus("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)?1:0); 296 this.alipayService.updateSFPayOrder(payOrder); 297 rMap.put("info", "ok"); 298 } else { 299 if ("ACQ.TRADE_NOT_EXIST".equals(alipayTradeQueryResponse.getSubCode())){ 300 if (payOrder != null) { 301 payOrder.setOrderStatus(0); 302 payOrder.setQueryStatus(1); 303 payOrder.setQueryTime(cdate); 304 payOrder.setPayStatus(0); 305 this.alipayService.updateSFPayOrder(payOrder); 306 } 307 }else { 308 if (payOrder != null) { 309 payOrder.setQueryTime(cdate); 310 payOrder.setQueryStatus(2); 311 this.alipayService.updateSFPayOrder(payOrder); 312 } 313 } 314 rMap.put("info", "alipayError"); 315 } 316 this.setJsonObject(response, rMap); 317 } catch (Exception e) { 318 e.printStackTrace(); 319 } 320 } 321 /** 322 * 检查恢复购买 323 * @param request 324 * @param response 325 * @param version 326 */ 327 @RequestMapping(value="{version}/alipay/checkRePurchase.htm",method={RequestMethod.POST}) 328 void checkRepurchase(HttpServletRequest request,HttpServletResponse response,@PathVariable(value="version") String version){ 329 Map<String,Object> rMap = new HashMap<String, Object>(); 330 try { 331 Map<String, String> reqPara = this.getReqPara(request, version, false); 332 String openId = reqPara.get("openId");//用户支付宝唯一标识 333 if(StringUtils.isBlank(openId)){ 334 rMap.put("retCode", 0); 335 rMap.put("retMsg", "Error openId!"); 336 this.setJsonObject(response, rMap, reqPara); 337 return; 338 } 339 /** 340 * 获得app传入的用户唯一标识,产品唯一标识,产品购买渠道标识,查询数据库,检验用户是否已购买该服务,返回结果给app端 341 * */ 342 MyUtil mu = MyUtil.getInstance(); 343 Date ctime = mu.getCurrenTime(); 344 // 组织查询订单的请求数据 345 try { 346 //先查询是否支付宝支付回调结果,不存在平台查询支付结果 347 SFPayOrder payOrder = productService.getPayOrderByOpenId(openId); 348 SFPayQueryOpenidLog queryOpenidLog = new SFPayQueryOpenidLog(); 349 if(payOrder!=null){ 350 if(-1==payOrder.getPayStatus()){ 351 SFProduct product = InitUtil.getProduct(payOrder.getProductId()); 352 if(product == null){ 353 rMap.put("retCode", 0); 354 rMap.put("retMsg", "Product does not exist " + payOrder.getProductId()); 355 this.setJsonObject(response, rMap, reqPara); 356 return; 357 } 358 //调用接口查询 359 Date cdate = mu.getCurrenTime(); 360 AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest(); 361 AlipayTradeQueryModel model = new AlipayTradeQueryModel(); 362 model.setOutTradeNo(payOrder.getOrderId()); 363 alipayTradeQueryRequest.setBizModel(model); 364 AlipayClient alipayClient = null; 365 if(alipayClientMap!=null && alipayClientMap.containsKey(payOrder.getProductId())){ 366 alipayClient = alipayClientMap.get(payOrder.getProductId()); 367 } 368 if(alipayClient==null){ 369 alipayClient = new DefaultAlipayClient(AlipayConfig.URL, product.getAlipayAppId(), product.getAlipayPrivateKey(),AlipayConfig.FORMAT, AlipayConfig.CHARSET, product.getAlipayPublicKey(), AlipayConfig.SIGNTYPE); 370 alipayClientMap.put(payOrder.getProductId(), alipayClient); 371 } 372 AlipayTradeQueryResponse alipayTradeQueryResponse; 373 try{ 374 alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest); 375 }catch (Exception e){ 376 if (payOrder != null) { 377 payOrder.setQueryTime(cdate); 378 payOrder.setQueryStatus(2); 379 this.alipayService.updateSFPayOrder(payOrder); 380 } 381 rMap.put("retCode", 0); 382 rMap.put("retMsg", "An error occurred"); 383 this.setJsonObject(response, rMap, reqPara); 384 return; 385 } 386 if (alipayTradeQueryResponse.isSuccess()) { 387 String orderStatus = alipayTradeQueryResponse.getTradeStatus(); 388 if("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)){//交易成功 389 rMap.put("retCode", 1); 390 rMap.put("retMsg", orderStatus); 391 }else{//交易失败 392 rMap.put("retCode", 0); 393 rMap.put("retMsg", orderStatus); 394 } 395 this.setJsonObject(response, rMap, reqPara); 396 397 payOrder.setPayStatus("TRADE_SUCCESS".equals(orderStatus) || "TRADE_FINISHED".equals(orderStatus)?1:0); 398 payOrder.setOrderStatus(1);//订单状态默认成功 399 payOrder.setQueryStatus(1); 400 payOrder.setQueryTime(cdate); 401 payOrder.setTransactionId(alipayTradeQueryResponse.getTradeNo()); 402 payOrder.setOpenId(alipayTradeQueryResponse.getBuyerUserId()); 403 payOrder.setUserAccount(alipayTradeQueryResponse.getBuyerLogonId()); 404 payOrder.setPayTime(alipayTradeQueryResponse.getSendPayDate()); 405 payOrder.setPayMsg(orderStatus); 406 this.alipayService.updateSFPayOrder(payOrder); 407 } else { 408 rMap.put("retCode", 0); 409 rMap.put("retMsg", alipayTradeQueryResponse.getSubMsg()); 410 this.setJsonObject(response, rMap, reqPara); 411 //交易不存在 412 if ("ACQ.TRADE_NOT_EXIST".equals(alipayTradeQueryResponse.getSubCode())){ 413 if (payOrder != null) { 414 payOrder.setQueryStatus(1); 415 payOrder.setOrderStatus(0); 416 payOrder.setQueryTime(cdate); 417 payOrder.setPayStatus(0); 418 this.alipayService.updateSFPayOrder(payOrder); 419 } 420 }else { 421 if (payOrder != null) { 422 payOrder.setQueryTime(cdate); 423 payOrder.setQueryStatus(2); 424 this.alipayService.updateSFPayOrder(payOrder); 425 } 426 } 427 } 428 return; 429 } 430 // 支付成功 431 rMap.put("retCode", payOrder.getPayStatus()==1?1:0); 432 rMap.put("retMsg", payOrder.getPayMsg()); 433 //rMap.put("failStatus", 0); 434 if(payOrder.getQueryStatus()!=1){ 435 payOrder.setQueryStatus(1); 436 payOrder.setQueryTime(ctime); 437 asyncInsertService.updateObject(payOrder); 438 } 439 queryOpenidLog.setoId(payOrder.getId()); 440 queryOpenidLog.setOrderId(payOrder.getOrderId()); 441 queryOpenidLog.setPayStatus(payOrder.getPayStatus()); 442 queryOpenidLog.setTransactionId(payOrder.getTransactionId()); 443 if(payOrder.getPayStatus()==1){ 444 queryOpenidLog.setQueryStatus(1); 445 }else{ 446 queryOpenidLog.setQueryStatus(0); 447 } 448 }else{ 449 // 平台支付回调结果 450 rMap.put("retCode", 0); 451 rMap.put("retMsg", "Not pay data!"); 452 //rMap.put("failStatus", 0); 453 queryOpenidLog.setQueryStatus(0); 454 } 455 this.setJsonObject(response, rMap, reqPara); 456 457 queryOpenidLog.setCtime(ctime); 458 queryOpenidLog.setImei(reqPara.get("imei")); 459 queryOpenidLog.setUuId(reqPara.get("uuId")); 460 queryOpenidLog.setOpenId(openId); 461 queryOpenidLog.setSpbillCreateIp(reqPara.get("clientIp")); 462 queryOpenidLog.setUserAgent(request.getHeader("User-Agent")); 463 if(mu.isNumber(reqPara.get("versionCode"))){ 464 queryOpenidLog.setVersionCode(Integer.valueOf(reqPara.get("versionCode"))); 465 } 466 if(mu.isNumber(reqPara.get("osType"))){ 467 queryOpenidLog.setOsType(Integer.valueOf(reqPara.get("osType"))); 468 } 469 queryOpenidLog.setVersionName(reqPara.get("versionName")); 470 this.asyncInsertService.addInsertObject(queryOpenidLog); 471 472 log.debug("结束调用支付宝订单openId查询接口..."); 473 } catch (Exception e) { 474 rMap.put("retCode", 0); 475 rMap.put("retMsg", "fail 查询失败"); 476 rMap.put("failStatus", 1); 477 response.setStatus(203); 478 this.setJsonObject(response, rMap, reqPara); 479 } 480 } catch (Exception e) { 481 e.printStackTrace(); 482 } 483 } 484 /** 485 * 应用网关,用于接收支付宝异步通知 486 * @throws UnsupportedEncodingException 487 * @throws ParseException 488 */ 489 @RequestMapping(value="/alipay/getAsyncAliPayNotice.htm",method={RequestMethod.POST,RequestMethod.GET}) 490 void getAsyncAliPayNotice(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, ParseException, AlipayApiException{ //获取支付宝POST过来反馈信息 491 log.info("-----------------------------------start get alipay async info----------------------------------------------------------"); 492 Map<String,String> params = new HashMap<String,String>(); 493 Map requestParams = request.getParameterMap(); 494 for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { 495 String name = (String) iter.next(); 496 String[] values = (String[]) requestParams.get(name); 497 String valueStr = ""; 498 for (int i = 0; i < values.length; i++) { 499 valueStr = (i == values.length - 1) ? valueStr + values[i] 500 : valueStr + values[i] + ","; 501 } 502 //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化 503 //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk"); 504 params.put(name, valueStr); 505 } 506 log.info("支付宝异步通知:["+params.toString()+"]"); 507 508 //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)// 509 String trade_no = request.getParameter("trade_no"); // 支付宝交易号 510 String out_trade_no = request.getParameter("out_trade_no"); // 获取订单号 511 String notify_time = request.getParameter("notify_time"); // 通知的发送时间。格式为yyyy-MM-dd HH:mm:ss 512 String trade_status = request.getParameter("trade_status"); // 交易状态 513 String buyer_id = request.getParameter("buyer_id"); // 买家支付宝账号对应的支付宝唯一用户号。 514 String buyer_logon_id = request.getParameter("buyer_logon_id"); // 买家支付宝账号 515 String payAppId = (request.getParameter("app_id")+"").trim(); 516 //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)// 517 try { 518 boolean flag = AlipaySignature.rsaCheckV1(params, InitUtil.getPayApiKey("ali"+payAppId), AlipayConfig.CHARSET,AlipayConfig.SIGNTYPE); 519 response.setContentType("text/plain;charset=utf-8"); 520 PrintWriter responseStream = response.getWriter(); 521 SFPayOrder payOrder = this.alipayService.getSFPayOrderByOrderId(out_trade_no); 522 if(flag){//验证签名通过 523 if(payOrder != null){//记录存在 524 if("TRADE_FINISHED".equals(trade_status) || "TRADE_SUCCESS".equals(trade_status)){ //交易成功 525 payOrder.setPayStatus(1); 526 }else{ 527 payOrder.setPayStatus(0); 528 } 529 payOrder.setUserAccount(buyer_logon_id); 530 payOrder.setOpenId(buyer_id); 531 payOrder.setTransactionId(trade_no); 532 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 533 payOrder.setPayMsg(trade_status); 534 payOrder.setPayTime(sdf.parse(notify_time)); 535 payOrder.setNotifyTime(new Date()); 536 this.alipayService.updateSFPayOrder(payOrder); 537 }else{//本地数据库中没有该条记录,基本上不会执行此步骤 538 payOrder = new SFPayOrder(); 539 payOrder.setOrderStatus(1); 540 if("TRADE_FINISHED".equals(trade_status) || "TRADE_SUCCESS".equals(trade_status)){ //交易成功 541 payOrder.setPayStatus(1); 542 }else{ 543 payOrder.setPayStatus(0); 544 } 545 payOrder.setOrderMsg("OK"); 546 payOrder.setPkgType(InitUtil.payPkgTypeMap.get("ali"+payAppId)); 547 payOrder.setOrderId(out_trade_no); 548 549 payOrder.setUserAccount(buyer_logon_id); 550 payOrder.setOpenId(buyer_id); 551 payOrder.setTransactionId(trade_no); 552 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 553 payOrder.setPayMsg(trade_status); 554 payOrder.setPayTime(sdf.parse(notify_time)); 555 payOrder.setNotifyTime(new Date()); 556 this.alipayService.saveOrderInfoToLocal(payOrder); 557 } 558 responseStream.print("success"); //请不要修改或删除 559 }else{ 560 responseStream.print("fail"); 561 } 562 responseStream.close(); 563 }catch (IOException e) { 564 e.printStackTrace(); 565 } 566 log.info("-----------------------------------end get alipay async info----------------------------------------------------------"); 567 } 568 569 /** 570 * APP向服务器请求支付宝认证加密信息。 571 * @throws Exception 572 */ 573 @RequestMapping(value="{version}/alipay/appGetOauthInfo.htm",method={RequestMethod.POST}) 574 void appGetOauthInfo(HttpServletRequest request,HttpServletResponse response,@PathVariable(value="version") String version) throws Exception{ 575 Map<String, Object> rMap = new HashMap<String, Object>(); 576 try { 577 Map<String, String> reqPara = this.getReqPara(request, version, false); 578 int productId = reqPara.get("productId")==null?1001:Integer.valueOf(reqPara.get("productId")); 579 if(productId==0){ 580 productId = 1001; 581 } 582 //*****************根据产品id查询产品******************** 583 //SFProduct product = this.alipayService.getProductByProductId(productId); 584 SFProduct product = InitUtil.getProduct(productId); 585 if(product == null){ 586 rMap.put("retCode", 0); 587 rMap.put("retMsg", "Product does not exist"); 588 this.setJsonObject(response, rMap, reqPara); 589 return; 590 } 591 //************************************* 592 boolean rsa2 = true ;//app通知服务器加密方式 593 Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(product.getAlipayPid(), product.getAlipayAppId(), product.getAlipayTargetId(), rsa2); 594 String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap); 595 String privateKey = rsa2 ? product.getAlipayPrivateKey() : product.getAlipayPrivateKey(); 596 String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, rsa2); 597 final String authInfo = info + "&" + sign; 598 //返回数据 599 rMap.put("retCode", 1); 600 rMap.put("retMsg", ""); 601 rMap.put("authInfo", authInfo); 602 this.setJsonObject(response, rMap, reqPara); 603 } catch (Exception e) { 604 e.printStackTrace(); 605 rMap.put("retCode", 0); 606 rMap.put("retMsg", "ERROR"); 607 this.setJsonObject(response, rMap); 608 } 609 } 610 611 612 }