LoveEmperor-王子様 支付宝内置浏览器支付 js+java

作者:LoveEmperor-王子様 

背景:支付宝内置浏览器支付,即支付宝扫码浏览应用页面,在页面上进行支付操作;  
     需要获取用户id,去请求支付宝下单

   [微信内置浏览器支付思路一样](https://blog.csdn.net/qq_31424825/article/details/80272364)
   支付宝参考地址:https://docs.open.alipay.com/53/104114  

js:

   var aliappid = "";
   var parameters = {};
    function is_weixn(){

        if (/MicroMessenger/.test(window.navigator.userAgent)) {
            // alert('微信客户端');
            parameters.containers = "wechat";
            getWxAppId();
        } else if (/AlipayClient/.test(window.navigator.userAgent)) {
            // alert('支付宝客户端');
           // window.location.href = "Payment.html";
            parameters.containers = "alipay";
            getAliCode();
        } else {
            // alert('其他浏览器');
        }
    }

    //从java端获取到支付宝appid,通过自动点击a标签达到用户自动授权,跳转目标页面  
    function getAliCode() {
        $.ajax({
            type: 'POST',
            data:parameters,
            url:currentProjectsHost+"/wxapp/mobileApi/getAliCode.fgl?",
            success: function(res){
                aliappid = res.aliAppId;
                var nextUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?redirect_uri="+redirect_urls+"&app_id="+aliappid+"&scope=auth_base&state=fgl2018";
                document.getElementById("authorization").href=nextUrl;
                xwzLoadHide();
                // setTimeout(function () {
                    document.getElementById("authorization").click();
                // },800)
            },error:function(res){
                xwzLoadHide();
            }
        });
    }
    is_weixn();
//目标页面获取用户授权后的code,提交给java 
next js:
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    var queryParameters = {};
    function clientSide() {
        if (/MicroMessenger/.test(window.navigator.userAgent)) {
            queryParameters.containers = "wechat";
            if (IisFirstDo === 1){submitCode();}
        } else if (/AlipayClient/.test(window.navigator.userAgent)) {
            queryParameters.containers = "alipay";
            alicodeSubmit();
        } else {}
    }

    var alicode = getQueryString('auth_code');
    //执行顺序
    function alicodeSubmit() {
        if(alicode!= null){
        window.localStorage.setItem("submitRoadInsideCode","false");
        submitRoadInsideCode = "false";
        var alicodeParameters = {};
        alicodeParameters.auth_code = alicode;
        $.ajax({
            type: 'POST',
            data: alicodeParameters,
            url: currentProjectsHost + "/wxapp/mobileApi/submitAlicode.fgl?",
            success: function (res) {
                window.localStorage.setItem("submitRoadInsideCode","true");
                submitRoadInsideCode = "true";
            }, error: function (res) {}
        });
        }
    }

        clientSide();
        /**
         * 支付宝支付信息,需要alijssdk
         */
        function doAliPrepare() {
            function ready(callback) {
                // 如果jsbridge已经注入则直接调用
                if (window.AlipayJSBridge) {
                    callback && callback();
                } else {
                    // 如果没有注入则监听注入的事件
                    document.addEventListener('AlipayJSBridgeReady', callback, false);
                }
            }
            ready(function() {
                    AlipayJSBridge.call('getNetworkType', function(result) {
                        if (JSON.stringify(result.networkAvailable) == 'true'){
                            getAlipayInfo()
                        }else {
                            valid.messageShowFn("网络不小心出错啦!");
                        }

                    });
            });
        }
//从java端请求的支付数据,唤起支付
        function getAlipayInfo() {
            var queryOptions = {};
            queryOptions.payFee = actualPayWX;
            queryOptions.payPurpose = "iParking";
            $.ajax({
                async: true,
                type: 'post',
                dataType: 'json',
                url: currentProjectsHost + "/wxapp/mobileApi/getalipayinfo.fgl",
                data: queryOptions,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                },
            success: function (result) {
                if (result.msg == 'ok') {
                    var param = eval('(' + result.aliOrderMsg + ')').alipay_trade_create_response;
                    // alert("=="+doPayOnce);
                    AlipayJSBridge.call("tradePay", {
                        tradeNO: param.trade_no
                    }, function(result) {
                        // alert(JSON.stringify(result));
                        if (result.resultCode  == "9000") {
                            if( ipayed  == "end"){
                                doAgainQuery();
                            }else {
                                window.location.href = currentProjectsHost + "/wxapp/roadinside/view/Payafter.html";
                            }
                        }else {
                            doPayOnce = 1;
                            $("#doPaybtn").css("backgroundColor","#980065");
                            valid.messageShowFn('亲,你支付失败了!', 14);
                        }
                    });
                }
            }
        });
    }

java:

    /**
         * 下放appid
         * @param request
         * @param response
         * @return
         * @throws IOException
         */
        @ResponseBody
        @RequestMapping(value=Url.GET_ALICODE_URL)  
        private AliAppIdInfoDto getAlicode(HttpServletRequest request,HttpServletResponse response) throws IOException{
            AliAppIdInfoDto dto = new AliAppIdInfoDto();
            String containers = request.getParameter("containers");
            if ("alipay".equals(containers)) {
                dto.setAliAppId(AliH5PayUtil.getString("ali.h5.pay.appid"));
                String wxOfficialAccount  = WeixinConfigUtil.getString("wxOfficialAccountUrl");
                if (wxOfficialAccount != null) {
                    dto.setWxOfficialAccount(wxOfficialAccount);
                }else {
                    dto.setWxOfficialAccount("noHaveUrl");
                }
                dto.setMsg("ok");
                dto.setRet(0);
            }else {
                dto.setMsg("请用支付宝客户端打开");
                dto.setRet(-1);
            }

            return dto;
        };

    @ResponseBody
    @RequestMapping(value=Url.SUBMIT_ALICODE_URL)  
    private BaseDTO submitAlicode(HttpServletRequest request,HttpServletResponse response) throws IOException{
        BaseDTO dto = new BaseDTO();
            response.setContentType("text/html");  
            response.setCharacterEncoding("UTF-8");  
            request.setCharacterEncoding("UTF-8");  
            String auth_code="";  
             auth_code=request.getParameter("auth_code");  
             AlipayClient client= alipayClient();  
                AlipaySystemOauthTokenRequest req = new AlipaySystemOauthTokenRequest();  
                req.setCode(auth_code);  
                req.setGrantType("authorization_code");  
                String userId="";  

                try {  //execute
                     AlipaySystemOauthTokenResponse asotr=client.execute(req);  
                     if(asotr.isSuccess()){
                         userId = asotr.getUserId();
                             if (userId != null) {
                                 AliRoadUserInfo roaduser = new AliRoadUserInfo();
                                 AliRoadUserInfo roaduser2 = aliRoadUserInfoService.queryAliRoadUserByBuyerId(userId);
                                 if (roaduser2 ==null ) {
                                     roaduser.setBuyerId(userId);
                                     roaduser.setCreateTime(databaseDAO.selectDatabaseSysDate());
                                     aliRoadUserInfoService.insetAliRoadUser(roaduser);
                                }
                                Cookie openidCookie = new Cookie("myAliBuyerId", userId);  
                                openidCookie.setMaxAge(60*60*24*10);//10天
                                openidCookie.setPath("/");  
                                response.addCookie(openidCookie);
                                dto.setMsg("ok");
                                dto.setRet(0);
                            }
                         } 
                } catch (Exception e) {  
                    e.printStackTrace();  
                }
                return dto;  
    };

    private DefaultAlipayClient alipayClient(){  
        DefaultAlipayClient alipayclient=new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliH5PayUtil.getString("ali.h5.pay.appid"), AliH5PayUtil.getString("ali.h5.pay.private.key"), "JSON", "GBK", AliH5PayUtil.getString("ali.h5.pay.alipay.public.key"), "RSA2");  
        return alipayclient;  
    } 

    /**
     * 支付宝支付信息
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value=Url.GET_ALIPAYINFO_URL)
    public IAlipayinfoDto getAlipayInfo(HttpServletRequest request,HttpServletResponse response) throws IOException{
        IAlipayinfoDto dto = new IAlipayinfoDto();
        int  totalFee;
        totalFee = Integer.valueOf(request.getParameter("payFee"));
        String NotifyUrl = "mobileApi/alipayh5NotifyUrl.fgl";
        String userid = "";
        Cookie[] cookies = request.getCookies();
           if(null==cookies) {  
               dto.setMsg("userid is null"); 
               dto.setRet(-10001);
               return dto;
           }else{  
               for(Cookie cookie : cookies){  
                   if ("myAliBuyerId".equals(cookie.getName())) {
                       userid = cookie.getValue();
                       if (null == userid) {
                           dto.setMsg("userid is null"); 
                           dto.setRet(-10001);
                           return dto;
                      }else {
                         try {  
                            AliRoadUserPayInfo payuser = new AliRoadUserPayInfo();
                            payuser.setBuyerId(userid);
                            payuser.setOutTradeNo(OrderUtil.getOrderNumber("ALIH5"));

                            AlipayTradeCreateResponse resp=AliPayOrder.makeOrder(AliPayOrder.getTestPayRequest(NotifyUrl,userid,payuser.getOutTradeNo(),totalFee));  
                            if(resp.isSuccess()){  
//                              System.out.println(resp.getBody());  
                                dto.setRet(0);
                                dto.setMsg("ok");
                                dto.setAliOrderMsg(resp.getBody());

                                AliRoadUserInfo roadUserInfo = aliRoadUserInfoService.queryAliRoadUserByBuyerId(userid);
                                if (roadUserInfo != null) {
                                    payuser.setLicense(roadUserInfo.getLicense());
                                    payuser.setRole(roadUserInfo.getRole());
                                    payuser.setChargeMoney(totalFee);
                                    payuser.setQrscene("1");
                                    payuser.setArriveTime(roadUserInfo.getArriveTime());
                                    payuser.setCheckTime(roadUserInfo.getCheckTime());
                                    payuser.setCreateTime(databaseDAO.selectDatabaseSysDate());
                                    payuser.setSpotnum(roadUserInfo.getSpotnum());
                                    payuser.setRemark(WeixinConfigUtil.getString("ROADINSIDEPAY"));
                                }
                                aliRoadUserPayService.insetAliRoadUser(payuser);


                            }else{  
                                System.out.println("下单失败");
                            }  
                        } catch (AlipayApiException e) {  
                            e.printStackTrace();  
                        }
                    }
                }
               }  
           } 

        return dto;
    }

/**
     * 支付宝回调
     * @param request
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value=Url.ALIPAY_H5_NOTIFY)
    public void alipayh5Notify(HttpServletRequest request,HttpServletResponse response) throws IOException{
           response.setContentType("text/html");  
           request.setCharacterEncoding("UTF-8");  
           response.setCharacterEncoding("UTF-8");  

         //交易状态
         String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
         String status = "1";
           if ("TRADE_SUCCESS".equals(trade_status)) {
               //商户订单号  
               String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
               log.info("商户订单:"+out_trade_no);
               AliRoadUserPayInfo payRecord = aliRoadUserPayService.queryChargeHistorByOutTradeNo(out_trade_no);
               if ("3".equals(payRecord.getStatus())) {
                   PrintWriter out = response.getWriter();  
                   System.out.println("通知支付宝成功结果");  
                   out.print("success");
                   out.flush();  
                   out.close();  
                }else {
                    status = "3";
                    String payMethod = "alipay";
                    String checkTime = payRecord.getCheckTime().toString();
                       //支付宝交易号  
                       String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
                    if ("0".equals(payRecord.getQrscene())) {
                         AckDTO<ReportPayInfoAckDto> reportPayAck;
                        try {
                            reportPayAck = PakringServerCom.reportPayInfos(new ReportPayInfoDto(payRecord.getChargeMoney(),payRecord.getLicense(),trade_no,out_trade_no,payRecord.getParkinglotNum(),payRecord.getArriveTime(),checkTime,payMethod));
                             log.info("reportPayAck"+reportPayAck.getStatus());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }else if ("1".equals(payRecord.getQrscene())) {
                             AckDTO<ReportPayInfoAckDto> roadreportPayAck;
                            try {
                                roadreportPayAck = PakringServerCom.roadReportPayInfo(new RoadReportPayInfoVo(payRecord.getChargeMoney(),payRecord.getLicense(),trade_no,out_trade_no,payRecord.getSpotnum(),payRecord.getArriveTime(),payMethod));
                                 log.info("roadreportPayAck"+roadreportPayAck.getStatus());
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }


                    }

                    payRecord.setTradeNo(trade_no);
                    payRecord.setUpdateTime(databaseDAO.selectDatabaseSysDate());
                    payRecord.setStatus(status);
                    aliRoadUserPayService.updateChargeHistorBy(payRecord);

                    PrintWriter out = response.getWriter();  
                       System.out.println("通知支付宝成功结果");  
                       out.print("success");
                       out.flush();  
                       out.close();  

                }

        }else {
            status = "4";
            log.info("支付宝支付失败!");
        }

    }

       public static AlipayTradeCreateResponse makeOrder(AlipayTradeCreateRequest req) throws AlipayApiException{  
            AlipayTradeCreateResponse  resp=null;  
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",AliH5PayUtil.getString("ali.h5.pay.appid"),AliH5PayUtil.getString("ali.h5.pay.private.key"),"JSON","GBK",AliH5PayUtil.getString("ali.h5.pay.alipay.public.key"),"RSA2");  
            resp =alipayClient.execute(req);  
            return  resp;  
        }  

        public static AlipayTradeCreateRequest getTestPayRequest(String NotifyUrl,String userid,String outTradeNo,int totalFee){
            AlipayTradeCreateRequest  req=new AlipayTradeCreateRequest ();  
            String notify_url=WeixinConfigUtil.getString("basePath")+NotifyUrl;  
            req.setNotifyUrl(notify_url);  
            JSONObject json=new JSONObject();  
            json.put("out_trade_no", outTradeNo);  
            if ("true".equals(AliH5PayUtil.getString("ali.h5.pay.test"))) {
                 json.put("total_amount", 0.01);  
            }else {
                json.put("total_amount", totalFee / 100); 
            }
            json.put("subject", WeixinConfigUtil.getString("ROADINSIDEPAY"));  
            json.put("buyer_id", userid);  
            String jsonStr=json.toString();  
            req.setBizContent(jsonStr);  
            return req;  
        }  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王子様~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值