微信、支付宝二码合一扫码支付实现思路(java)
一、支付二维码(预订单)
根据需要购买的信息创建预订单,将订单信息保存到Redis中,并设置有效期,注意生产二维码的链接后的参数可以关联到Redis中的key;
QRCode 为servlet扫码请求的URL;
UUIDUtils.getUUID() 为预订单单号,在servlet请求中截取,然后在Redis中查找对应的Key的数据;
二维码地址:http://kung900519.qicp.io/interface/QRCode/UUIDUtils.getUUID();
二、创建二维码扫码请求地址servlet:QRCodeServlet;微信支付重定向请求servlet:WechatPayServlet;支付宝重定向请求servlet:AliPayServlet;
QRCodeServlet 用于用户使用微信或者支付宝扫码二维码进行客户端识别及重定向到对应的业务处理;
packagecom.platform.cloudlottery.servlet; importjava.io.IOException; importjavax.servlet.ServletConfig; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.context.support.SpringBeanAutowiringSupport; importcom.platform.cloudlottery.common.CommonConfig; importcom.platform.cloudlottery.common.alipay.config.MyAliPayConfig; importcom.platform.cloudlottery.common.wechat.config.WXPublicConfig; importcom.platform.cloudlottery.common.wechat.util.HttpUtil; importcom.platform.cloudlottery.model.SysPayChannel; importcom.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl; importcom.platform.cloudlottery.web.StatusContant.PayTypeConstant; /** *@ClassName:QRCodeServlet *@Description:TODO(根据请求的后缀获取该数据编码对应的数据,并重定向到页面) *@authorchenkun *@date2018年12月29日 * */ publicclassQRCodeServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-8457626626670970403L; protectedLoggerlogger=LoggerFactory.getLogger(getClass()); privatestaticfinalStringUrlStr="QRCode/"; privatestaticfinalStringwechatPay="wechatPay/"; privatestaticfinalStringaliPay="aliPay/"; @Autowired privateSysPayChannelServiceImplpayChannelService; publicvoidinit(ServletConfigservletConfig)throwsServletException{ super.init(servletConfig); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,servletConfig.getServletContext()); } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ logger.info("####################请求开始####################"); StringuserAgent=request.getHeader("user-agent"); StringRequestURL=request.getRequestURL().toString(); logger.info("URL:"+RequestURL); StringReqInfo=RequestURL.substring(RequestURL.indexOf(UrlStr)+UrlStr.length()); logger.info("URL:"+ReqInfo); CommonConfigcommonConfig=newCommonConfig(); if(userAgent!=null&&userAgent.contains("AlipayClient")){ logger.info("来自支付宝"); Stringredirecturi=HttpUtil.urlEnCode(commonConfig.getDomain()+aliPay+ReqInfo); logger.info("REDIRECT_URI="+redirecturi); SysPayChannelchannel=payChannelService.selectByChannelType(PayTypeConstant.Alipay); MyAliPayConfigaliPayConfig=newMyAliPayConfig(); aliPayConfig.setAppId(channel.getAppid()); //授权页面地址 StringrequestUrl=aliPayConfig.getAuthgateway(); requestUrl=requestUrl.replace("APPID",aliPayConfig.getAppId()).replace("SCOPE",aliPayConfig.getScope()).replace("REDIRECT_URI",redirecturi); //重定向到授权页面 response.sendRedirect(requestUrl); }elseif(userAgent!=null&&userAgent.contains("MicroMessenger")){ logger.info("来自微信"); Stringredirecturi=HttpUtil.urlEnCode(commonConfig.getDomain()+wechatPay+ReqInfo); logger.info("REDIRECT_URI="+redirecturi); SysPayChannelchannel=payChannelService.selectByChannelType(PayTypeConstant.Wechat); WXPublicConfigpublicConfig=newWXPublicConfig(); publicConfig.setAppId(channel.getAppid()); publicConfig.setOriginId(channel.getOriginid()); publicConfig.setAppSecret(channel.getAppsecret()); publicConfig.setEncodingAESKey(channel.getEncodingaeskey()); //授权页面地址 StringrequestUrl=publicConfig.getAuthorizeinterface(); requestUrl=requestUrl.replace("APPID",publicConfig.getAppId()).replace("REDIRECT_URI",redirecturi).replace("SCOPE",publicConfig.getScope()).replace("STATE",publicConfig.getState()); //重定向到授权页面 response.sendRedirect(requestUrl); }else{ logger.info("未知来源"); } logger.info("####################请求结束####################"); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ doGet(request,response); } }
WechatPayServlet在获取到Redis中预订单数据后,创建真实订单并调用微信“统一下单接口”;
packagecom.platform.cloudlottery.servlet; importcom.alibaba.fastjson.JSONObject; importcom.github.wxpay.sdk.WXPayUtil; importcom.platform.cloudlottery.common.CommonConfig; importcom.platform.cloudlottery.common.jedis.JedisUtil; importcom.platform.cloudlottery.common.lang.StringUtils; importcom.platform.cloudlottery.common.utils.BusinessCodeUtils; importcom.platform.cloudlottery.common.wechat.bean.WeiXinOAuth2Token; importcom.platform.cloudlottery.common.wechat.bean.WeiXinUserInfo; importcom.platform.cloudlottery.common.wechat.config.WXPayConfig; importcom.platform.cloudlottery.common.wechat.config.WXPublicConfig; importcom.platform.cloudlottery.common.wechat.util.WeiXinOAuth2Util; importcom.platform.cloudlottery.common.wechat.util.WeiXinPayUtils; importcom.platform.cloudlottery.model.SysPayChannel; importcom.platform.cloudlottery.service.Impl.LotteryOrderServiceImpl; importcom.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl; importcom.platform.cloudlottery.service.Impl.UserMemberServiceImpl; importcom.platform.cloudlottery.service.OrderServcie; importcom.platform.cloudlottery.service.UserInfoService; importcom.platform.cloudlottery.web.ResultContant; importcom.platform.cloudlottery.web.StatusContant.PayTypeConstant; importcom.platform.cloudlottery.web.SysKey; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.web.context.support.SpringBeanAutowiringSupport; importredis.clients.jedis.Jedis; importjavax.servlet.ServletConfig; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.IOException; importjava.math.BigDecimal; importjava.util.Date; importjava.util.LinkedHashMap; importjava.util.Map; /** *@ClassName:WechatPayServlet *@Description:TODO(这里用一句话描述这个类的作用) *@authorchenkun *@date2019年1月5日 * */ publicclassWechatPayServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-8457626626670970403L; protectedLoggerlogger=LoggerFactory.getLogger(getClass()); privatestaticJedisredis=JedisUtil.getJedis(); @Value("${config.domain}") privateStringdomain; @Value("${config.isProduction}") privatebooleanisProduction; //请求路径包含的字符串 privatestaticfinalStringUrlStr="wechatPay/"; @Autowired privateSysPayChannelServiceImplpayChannelService; @Autowired privateUserMemberServiceImplmemberService; @Autowired privateLotteryOrderServiceImpllotteryOrderService; publicvoidinit(ServletConfigservletConfig)throwsServletException{ super.init(servletConfig); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,servletConfig.getServletContext()); } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ logger.debug("####################请求开始####################"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); try{ //用户同意授权后,能获取到code Stringcode=request.getParameter("code"); //用户同意授权 if(!"authdeny".equals(code)){ CommonConfigcommonConfig=newCommonConfig(); StringRequestURL=request.getRequestURL().toString(); logger.debug("URL:"+RequestURL); StringQRCodeUrl=RequestURL.substring(RequestURL.indexOf(UrlStr)+UrlStr.length()); StringQRCodeReqInfo=QRCodeUrl.split("&")[0]; StringoperatorId=QRCodeUrl.split("&")[1]; logger.debug("QRCodeReqInfo:"+QRCodeReqInfo+";operatorId:"+operatorId); Stringadvancekey=commonConfig.getLotteryorder()+QRCodeReqInfo; SysPayChannelchannel=payChannelService.selectByChannelType(PayTypeConstant.Wechat); WXPublicConfigpublicConfig=newWXPublicConfig(); publicConfig.setAppId(channel.getAppid()); publicConfig.setOriginId(channel.getOriginid()); publicConfig.setAppSecret(channel.getAppsecret()); publicConfig.setEncodingAESKey(channel.getEncodingaeskey()); WXPayConfigpayConfig=newWXPayConfig(); payConfig.setMchId(channel.getMchid()); payConfig.setAppId(channel.getAppid()); payConfig.setKey(channel.getWxkey()); payConfig.setApicertPath(channel.getPayCertUrl()); payConfig.setSpbillCreateIp(channel.getSpbillcreateip()); //获取网页授权access_token WeiXinOAuth2TokenweixinOauth2Token=WeiXinOAuth2Util.getOAuth2AccessToken(publicConfig,code); //网页授权接口访问凭证 StringaccessToken=weixinOauth2Token.getAccessToken(); logger.debug("accessToken="+accessToken); //用户标识 StringopenId=weixinOauth2Token.getOpenId(); logger.debug("openId="+openId); //获取用户信息 WeiXinUserInfouserInfo=WeiXinOAuth2Util.getOAuth2UserInfo(publicConfig,accessToken,openId); logger.debug(userInfo.getNickName()+"=====微信支付====="+userInfo.getOpenId()); //添加或更新用户信息 Stringuserid=UserInfoService.CreateUserMember(userInfo,memberService); if(!redis.exists(advancekey)){//判断key是否存在 logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } if(StringUtils.trimToEmpty(redis.get(advancekey)).equals("")){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } JSONObjectjsonObject=JSONObject.parseObject(redis.get(advancekey)); if(null==jsonObject){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } if(redis.get(advancekey+"_lock")!=null&&!redis.get(advancekey+"_lock").equals("")){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } redis.setex(advancekey+"_lock",1,"lock"); Stringorderid=BusinessCodeUtils.getOrderNo(jsonObject.getString(SysKey.deviceSn)); intmoney=jsonObject.getIntValue(SysKey.money); intlotterytype=jsonObject.getIntValue(SysKey.lotteryType); if(!orderid.equals("")&&money!=0){ //创建订单 booleanbool=OrderServcie.createorder(QRCodeReqInfo,PayTypeConstant.Wechat,payConfig.getAppID(),userid,openId,orderid,jsonObject,lotteryOrderService); if(bool){ //删除预订单信息 redis.del(advancekey);//一个预订单只能创建一个订单 Stringpaymoney=String.valueOf(money); if(!isProduction){//测试环境 paymoney=BigDecimal.valueOf(Long.valueOf(paymoney)).divide(newBigDecimal(100)).toString();//真实金额除100 } logger.debug("是否生产环境:"+isProduction+";订单金额为:"+String.valueOf(money)+";实际支付金额为:"+paymoney); //创建微信订单 Mapmap=WeiXinPayUtils.createOrderJsapi(domain,payConfig,orderid,paymoney,lotterytype==0?"即开票":"电脑票",openId); logger.debug("创建微信支付预订单返回数据:"+JSONObject.toJSONString(map)); if(map!=null){ if(map.get("return_code").equals("SUCCESS")){ if(map.get("result_code").equals("SUCCESS")){ logger.debug("创建微信支付预订单成功"); Map data=newLinkedHashMap (); data.put("appId",payConfig.getAppID()); data.put("timeStamp",String.valueOf(newDate().getTime()/1000)); data.put("nonceStr",WXPayUtil.generateNonceStr()); data.put("package","prepay_id="+map.get("prepay_id")); data.put("signType","MD5"); data.put("paySign",WXPayUtil.generateSignature(data,payConfig.getKey())); logger.debug("返回到客户端的数据:"+JSONObject.toJSONString(data)); request.setAttribute("appId",data.get("appId")); request.setAttribute("timeStamp",data.get("timeStamp")); request.setAttribute("nonceStr",data.get("nonceStr")); request.setAttribute("package",data.get("package")); request.setAttribute("signType",data.get("signType")); request.setAttribute("paySign",data.get("paySign")); request.setAttribute("code",ResultContant.sucess); request.setAttribute("message","成功"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败;订单金额或者订单号数据有误"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } } }catch(Exceptione){ e.printStackTrace(); logger.debug("系统异常"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../wechat/WechatPay.jsp").forward(request,response); } logger.debug("####################请求结束####################"); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ doGet(request,response); } }
AliPayServlet 在获取到Redis中预订单数据后,创建真实订单并调用支付宝“手机网站支付接口”;
packagecom.platform.cloudlottery.servlet; importcom.alibaba.fastjson.JSONObject; importcom.platform.cloudlottery.common.CommonConfig; importcom.platform.cloudlottery.common.alipay.bean.AliPayOAuth2Token; importcom.platform.cloudlottery.common.alipay.bean.AliPayUserInfo; importcom.platform.cloudlottery.common.alipay.config.MyAliPayConfig; importcom.platform.cloudlottery.common.alipay.uitl.AliPayOAuth2Util; importcom.platform.cloudlottery.common.alipay.uitl.AlipayPayUtils; importcom.platform.cloudlottery.common.jedis.JedisUtil; importcom.platform.cloudlottery.common.lang.StringUtils; importcom.platform.cloudlottery.common.properties.PropertiesUtils; importcom.platform.cloudlottery.common.utils.BusinessCodeUtils; importcom.platform.cloudlottery.model.SysPayChannel; importcom.platform.cloudlottery.service.Impl.LotteryOrderServiceImpl; importcom.platform.cloudlottery.service.Impl.SysPayChannelServiceImpl; importcom.platform.cloudlottery.service.Impl.UserMemberServiceImpl; importcom.platform.cloudlottery.service.OrderServcie; importcom.platform.cloudlottery.service.UserInfoService; importcom.platform.cloudlottery.web.ResultContant; importcom.platform.cloudlottery.web.StatusContant.PayTypeConstant; importcom.platform.cloudlottery.web.SysKey; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.web.context.support.SpringBeanAutowiringSupport; importredis.clients.jedis.Jedis; importjavax.servlet.ServletConfig; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.IOException; importjava.math.BigDecimal; importjava.util.Properties; /** *@ClassName:AliPayServlet *@Description:TODO(这里用一句话描述这个类的作用) *@authorchenkun *@date2019年1月5日 * */ publicclassAliPayServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-8457626626670970403L; protectedLoggerlogger=LoggerFactory.getLogger(getClass()); privatestaticJedisredis=JedisUtil.getJedis(); @Value("${config.domain}") privateStringdomain; @Value("${config.isProduction}") privatebooleanisProduction; //请求路径包含的字符串 privatestaticfinalStringUrlStr="aliPay/"; @Autowired privateSysPayChannelServiceImplpayChannelService; @Autowired privateUserMemberServiceImplmemberService; @Autowired privateLotteryOrderServiceImpllotteryOrderService; publicvoidinit(ServletConfigservletConfig)throwsServletException{ super.init(servletConfig); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,servletConfig.getServletContext()); } publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ logger.debug("####################请求开始####################"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); try{ //用户同意授权后,能获取到code Stringcode=request.getParameter("auth_code"); //用户同意授权 if(!code.equals("")){ CommonConfigcommonConfig=newCommonConfig(); //具体业务 StringRequestURL=request.getRequestURL().toString(); logger.debug("URL:"+RequestURL); StringQRCodeUrl=RequestURL.substring(RequestURL.indexOf(UrlStr)+UrlStr.length()); StringQRCodeReqInfo=QRCodeUrl.split("&")[0]; StringoperatorId=QRCodeUrl.split("&")[1]; logger.debug("QRCodeReqInfo:"+QRCodeReqInfo+";operatorId:"+operatorId); Stringadvancekey=commonConfig.getLotteryorder()+QRCodeReqInfo; SysPayChannelchannel=payChannelService.selectByChannelType(PayTypeConstant.Alipay); MyAliPayConfigaliPayConfig=newMyAliPayConfig(); aliPayConfig.setAppId(channel.getAppid()); Stringcertsrc=channel.getPayCertUrl(); PropertiespropertiesFile=PropertiesUtils.getPropertiesFile(certsrc); if(propertiesFile!=null){ aliPayConfig.setPayeeAccount(propertiesFile.getProperty("ALI_PAYEE_ACCOUNT")); aliPayConfig.setAppId(propertiesFile.getProperty("ALI_APP_ID")); aliPayConfig.setAliPayPublicKey(propertiesFile.getProperty("ALI_ALIPAY_PUBLIC_KEY")); aliPayConfig.setAppPayPublicKey(propertiesFile.getProperty("ALI_APP_PAY_PUBLIC_KEY")); aliPayConfig.setAppPrivateKey(propertiesFile.getProperty("ALI_APP_PRIVATE_KEY")); } //获取网页授权access_token AliPayOAuth2TokenaliPayOAuth2Token=AliPayOAuth2Util.getOAuth2AccessToken(aliPayConfig,code); //网页授权接口访问凭证 StringaccessToken=aliPayOAuth2Token.getAccessToken(); logger.debug("accessToken="+accessToken); //用户标识 Stringaliuserid=aliPayOAuth2Token.getUserid(); logger.debug("aliuserid="+aliuserid); //获取用户信息 AliPayUserInfouserInfo=AliPayOAuth2Util.getOAuth2UserInfo(aliPayConfig,accessToken,aliuserid); logger.debug(userInfo.getNickName()+"=====支付宝支付====="+userInfo.getUserId()); //添加或更新用户信息 Stringuserid=UserInfoService.CreateUserMember(userInfo,memberService); if(!redis.exists(advancekey)){//判断key是否存在 logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } if(StringUtils.trimToEmpty(redis.get(advancekey)).equals("")){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } JSONObjectjsonObject=JSONObject.parseObject(redis.get(advancekey)); if(null==jsonObject){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } if(redis.get(advancekey+"_lock")!=null&&!redis.get(advancekey+"_lock").equals("")){ logger.debug("二维码失效"); request.setAttribute("code",ResultContant.notuserdqrcode); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); logger.debug("####################请求结束####################"); return; } redis.setex(advancekey+"_lock",1,"lock"); Stringorderid=BusinessCodeUtils.getOrderNo(jsonObject.getString(SysKey.deviceSn)); intmoney=jsonObject.getIntValue(SysKey.money); intlotterytype=jsonObject.getIntValue(SysKey.lotteryType); if(!orderid.equals("")&&money!=0){ //创建订单 booleanbool=OrderServcie.createorder(QRCodeReqInfo,PayTypeConstant.Alipay,aliPayConfig.getAppId(),userid,aliuserid,orderid,jsonObject,lotteryOrderService); if(bool){ //删除预订单信息 redis.del(advancekey);//一个预订单只能创建一个订单 Stringpaymoney=BigDecimal.valueOf(Long.valueOf(money)).divide(newBigDecimal(100)).toString(); if(!isProduction){//测试环境 paymoney=BigDecimal.valueOf(Long.valueOf(paymoney)).divide(newBigDecimal(100)).toString();//真实金额除100 } logger.debug("是否生产环境:"+isProduction+";订单金额为:"+BigDecimal.valueOf(Long.valueOf(money)).divide(newBigDecimal(100)).toString()+";实际支付金额为:"+paymoney); //创建支付宝订单 Stringresponsestr=AlipayPayUtils.createOrderWapPay(domain,aliPayConfig,orderid,lotterytype==0?"即开票":"电脑票",paymoney,""); logger.debug("创建支付宝支付预订单返回数据:"+responsestr); if(!responsestr.equals("")){ response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(responsestr);//直接将完整的表单html输出到页面 response.getWriter().flush(); response.getWriter().close(); response.getWriter().append("Servedat:").append(request.getContextPath()); }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败:创建支付预订单失败"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); } }else{ logger.debug("创建订单失败;订单金额或者订单号数据有误"); request.setAttribute("code",ResultContant.createordererror); request.setAttribute("message","创建订单失败"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); } } }catch(Exceptione){ e.printStackTrace(); logger.debug("系统异常"); request.setAttribute("code","二维码失效"); request.setAttribute("message","二维码失效"); request.getRequestDispatcher("../alipay/AliPay.jsp").forward(request,response); } logger.debug("####################请求结束####################"); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ doGet(request,response); } }
三、创建微信支付结果回调接口和支付宝支付接口回调接口,用于接收微信或者支付宝的支付结果通知;
aliPayNotify 支付宝支付成功回调接口
/** *@Title:aliPayNotify *@Description:TODO(支付宝支付成功过回调) *@authorchenkun *@return参数 *@returnString返回类型 *@throws */ @RequestMapping(value="/aliPayNotify",method=RequestMethod.POST) publicStringaliPayNotify(){ ServletRequestAttributesattributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequestrequest=attributes.getRequest(); Mapparams=convertRequestParamsToMap(request);//将异步通知中收到的待验证所有参数都存放到map中 StringparamsJson=JSON.toJSONString(params); logger.info("支付宝支付回调,{"+paramsJson+"}"); try{ SysPayChannelchannel=payChannelService.selectByChannelType(PayTypeConstant.Alipay); MyAliPayConfigaliPayConfig=newMyAliPayConfig(); aliPayConfig.setAppId(channel.getAppid()); Stringcertsrc=channel.getPayCertUrl(); PropertiespropertiesFile=PropertiesUtils.getPropertiesFile(certsrc); if(propertiesFile!=null){ aliPayConfig.setPayeeAccount(propertiesFile.getProperty("ALI_PAYEE_ACCOUNT")); aliPayConfig.setAppId(propertiesFile.getProperty("ALI_APP_ID")); aliPayConfig.setAliPayPublicKey(propertiesFile.getProperty("ALI_ALIPAY_PUBLIC_KEY")); aliPayConfig.setAppPayPublicKey(propertiesFile.getProperty("ALI_APP_PAY_PUBLIC_KEY")); aliPayConfig.setAppPrivateKey(propertiesFile.getProperty("ALI_APP_PRIVATE_KEY")); } //调用SDK验证签名 booleansignVerified=AlipaySignature.rsaCheckV1(params,aliPayConfig.getAliPayPublicKey(), aliPayConfig.getCharset(),aliPayConfig.getSigntype()); if(signVerified){ logger.info("支付宝回调签名认证成功"); //按照支付结果异步通知中的描述,对支付结果中的业务内容进行1\2\3\4二次校验,校验成功后在response中返回success,校验失败返回failure this.check(params); //另起线程处理业务 executorService.execute(newAliPayNotifyTask(params,payCallBackService)); //如果签名验证正确,立即返回success,后续业务另起线程单独处理 //业务处理失败,可查看日志进行补偿,跟支付宝已经没多大关系。 return"success"; }else{ logger.info("支付宝回调签名认证失败,signVerified=false,paramsJson:{}",paramsJson); return"failure"; } }catch(AlipayApiExceptione){ logger.error("支付宝回调签名认证失败,paramsJson:{},errorMsg:{}",paramsJson,e.getMessage()); return"failure"; } }
WechatPayNotify 微信支付成功回调
/** *@Title:WechatPayNotify *@Description:TODO(微信支付成功回调) *@authorchenkun *@return参数 *@returnString返回类型 *@throws */ @RequestMapping(value="/WechatPayNotify",method=RequestMethod.POST) publicStringWechatPayNotify(){ ServletRequestAttributesattributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequestrequest=attributes.getRequest(); Stringresult="";//返回给微信的处理结果 StringnotityXml="";//微信给返回的东西 StringinputLine; try{ while((inputLine=request.getReader().readLine())!=null){ notityXml+=inputLine; } request.getReader().close(); }catch(Exceptione){ logger.error("微信支付回调失败,paramsJson:{},errorMsg:{}","回调数据获取失败",e.getMessage()); result=setXml("fail","xml获取失败"); e.printStackTrace(); } if(StringUtils.isEmpty(notityXml)){ logger.info("微信支付回调失败:回调数据为空"); result=setXml("fail","xml为空"); } try{ logger.info("微信支付回调数据:{"+notityXml+"}"); Mapmap=WXPayUtil.xmlToMap(notityXml); Stringresult_code=(String)map.get("result_code");//业务结果 Stringreturn_code=(String)map.get("return_code");//SUCCESS/FAIL //解析各种数据 if(result_code.equals("SUCCESS")){ result=setXml("SUCCESS","OK"); }else{ logger.info("微信返回的交易状态不正确(result_code="+result_code+")"); result=setXml("fail","微信返回的交易状态不正确(result_code="+result_code+")"); } //如果微信返回的结果是success,则修改订单状态 if(return_code.equals("SUCCESS")){ //这里是我的业务........................................ Stringsr=payCallBackService.confirmWechatPayOrder(map,true); logger.debug(sr); if(StringUtils.isNotEmpty(sr)){ result=setXml("fail",sr); executorService.execute(newWechatPayRefundTask(map,payCallBackService)); }else{ result=setXml("SUCCESS","OK"); } }else{ result=setXml("fail",return_code); } }catch(Exceptione){ logger.error("微信支付回调失败,paramsJson:{},errorMsg:{}","回调数据处理失败",e.getMessage()); result=setXml("fail","回调数据处理失败"); e.printStackTrace(); } logger.info("回调成功----返回给微信的xml:"+result); returnresult; }
仅此供给大家,在大家有这方面的需求时,少走弯路!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。