Java手把手教你完成支付宝H5支付

1,阿里的H5支付相对来微信来说很简单,第一步我们需要获取以下几个参数

    // 商户appid-----h5支付的ID
    public static String        APPID             = "APPID";
    // 私钥 pkcs8格式的
    public static String        RSA_PRIVATE_KEY   =""
    // 服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    public static String        notify_url        = "https://此处域名/faint-service/f/ali/alipayRechargeGoldNotify";
    // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问       商户可以自定义同步跳转地址
    public static String        return_url        = "https://此处域名/faint-service/static/h5/app/successh5.html";
    // 请求网关地址
    public static String        URL               = "https://openapi.alipay.com/gateway.do";
    // 编码
    public static String        CHARSET           = "UTF-8";
    // 返回格式
    public static String        FORMAT            = "json";
    // 支付宝公钥
    public static String        ALIPAY_PUBLIC_KEY = ""
    // RSA2
    public static String        SIGNTYPE          = "RSA2";

APPID:怎样申请支付宝支付的整个流程我就不一一细说了,APPID在你申请APP支付的时候就可以得到此数据

RSA_PRIVATE_KEY 和ALIPAY_PUBLIC_KEY   :公钥私钥也是你申请APP支付会设置的数据

notify_url        :支付宝支付成功回调到服务器的地址,获得成功数据

return_url        如果是H5支付的话,需要填写,APP支付不需要,支付成功返回的页面.

URL              :此URL是把数据打包到支付宝  唤醒支付宝支付的地址

CHARSET            FORMAT            SIGNTYPE          :这三个是固定死的,填就完事

2,开始写代码了,前端请求支付,后端处理数据,打包到支付宝服务器

@RequestMapping("aliPayRechargeGold")
    public void CreatPayOrderForH5(HttpServletRequest request, HttpServletResponse response, Integer rechargeNumber, String rechargeId) {
        try {
            //如果是模拟请求则返回null
            boolean bool = rechargeList.contains(rechargeId);
            
                //保存充值记录到数据库
                int aisle = 2; //支付宝充值
                AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APPID, AliPayConfig.RSA_PRIVATE_KEY, "json", "UTF-8", AliPayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                Integer money = mdRecharge.getRmb();//获取金额,单位元
                String reaMoney = money.toString() + ".00";
                order.put("out_trade_no", mdRecharge.getNumber()); //订单号
                order.put("subject", ""); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", "");//商品名称
                order.put("total_amount", reaMoney); //金额
                alipayRequest.setBizContent(order.toString());
                //在公共参数中设置回跳和通知地址
                alipayRequest.setNotifyUrl(AliPayConfig.notify_url);
                alipayRequest.setReturnUrl(AliPayConfig.return_url);
                String form = alipayClient.pageExecute(alipayRequest).getBody();
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write(form);
                response.getWriter().flush();
                response.getWriter().close();
            
        } catch (AlipayApiException e) {
            logger.error("CreatPayOrderForH5", e);
        } catch (IOException e) {
            logger.error("CreatPayOrderForH5", e);
        }
    }

3,服务器收到支付宝支付成功的返回值

@ResponseBody
    @RequestMapping(value = "alipayRechargeGoldNotify", method = RequestMethod.POST)
    public String getNotify(HttpServletRequest request, HttpServletResponse response) {
        logger.info("AliController.getNotify=======start");
        Map requestParams = request.getParameterMap();
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator() ; iter.hasNext() ;) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0 ; i < values.length ; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                //乱码解决,这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
        }
        ///////////////////处理自己的逻辑//////////////////////
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, "UTF-8", "RSA2");
            if (flag) {
                if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
                    String orderSn = params.get("out_trade_no"); //商家订单号
                    String openid = params.get("buyer_id"); //买手ID
                    String moneyNumber = params.get("total_amount"); //实际支付金额
                    BigDecimal amountPay = new BigDecimal(moneyNumber);//将分转化为元的对象
                    //写自己的业务逻辑
                    logger.info("mdRechargeService.rechargeGoldTwo业务操作成功");
                }
                //签名验证成功
                response.getWriter().print("success");
                logger.info("flag签名验证成功");
            } else {
                // 验证失败
                response.getWriter().print("failure");
                logger.info("flag签名验证失败");
            }
        } catch (Exception e) {
            logger.info("flag签名获取订单信息异常");
        }
        logger.info("AliController.getNotify=======end");
        return null;
    }

 

4,关于前端H5页面的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>充值</title>
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/assets/mui/css/mui.min.css"  type="text/css">
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/css/border.css"  type="text/css">
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/css/reset.css"  type="text/css">
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/assets/font_jnyk9xz222/iconfont.css"  type="text/css">
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/css/topup.css"  type="text/css">
    <link rel="stylesheet" href="https://www.chujian.live/faint-service/static/project/mobile/css/main.css"  type="text/css">
 
    <script src="https://www.chujian.live/faint-service/static/project/mobile/assets/mui/js/mui.min.js"></script>
    <script src="https://www.chujian.live/faint-service/static/project/mobile/assets/zepto/zepto.min.js"></script>
    <script src="https://www.chujian.live/faint-service/static/project/mobile/assets/artTemplate/template-native.js"></script>
</head>
<body>
    <div class="mui-content">
        <!-- 充值账户 -->
        <div  class="account">
            <h1>充值账户</h1>
            <a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7ddca8845b6e588f&redirect_uri=https://www.chujian.live/faint-service/f/weixin/findMdRechargeList&response_type=code&scope=snsapi_base#wechat_redirect">充值记录</a>
            <input type="text" class="clear" id="rechargeNumber" placeholder="请输入您的隐隐ID">
            <input type="hidden" id="code" name="code" value="">
        </div>
        <div class="amount">
            <h1>充值金额</h1>
            <div class="grid mui-bar-tab">
                <a href="#" class="mui-tab-item mui-active"  data="6,396">
                    <i><p>396</p><p>金币</p></i>
                    <span>6元</span>
                </a>
                <a href="#" class="mui-tab-item"  data="30,1980">
                    <i><p>1980</p><p>金币</p></i>
                    <span>30元</span>
                </a>
                <a href="#" class="mui-tab-item"  data="60,3960">
                    <i><p>3960</p><p>金币</p></i>
                    <span>60元</span>
                </a>
                <a href="#" class="mui-tab-item"  data="108,7128">
                    <i><p>7128</p><p>金币</p></i>
                    <span>108元</span>
                </a>
                <a href="#" class="mui-tab-item" data="298,19668">
                    <i><p>19668</p><p>金币</p></i>
                    <span>298元</span>
                </a>
                <a href="#" class="mui-tab-item" data="648,42768">
                    <i><p>42768</p><p>金币</p></i>
                    <span>648元</span>
                </a>
            </div>
        </div>
        <!-- 微信支付 -->
        <div class="pay">
            <img src="https://www.chujian.live/faint-service/static/project/mobile/images/weixin.png" alt="">
            <h1>微信支付</h1>
        </div>
    </div>
    <!-- 底部--支付模块 -->
    <div class="footer" onclick="pay()">
        <h5>总价:</h5>
        <p id="fuzhi"><span>¥</span>6</p>
        <a id="a1">去支付</a>
    </div>
</body>
<script>
</script>

<script type="text/javascript">
    $('.mui-bar-tab').on('click','a',function(){
        var id= $('.mui-active').attr('data');
        var str = id.split(',');
        $('#fuzhi').text(str[0])
    })    
    // 解析url参数
    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var url=decodeURI(decodeURI(window.location.search))
        var r = url.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    function pay(){
        var anit = $(".footer");
        var rechargeNumber=$('#rechargeNumber').val();
        if(rechargeNumber.toString().length>8){
            alert("请输入正确的隐隐ID");
            return false;
        }
        var rechargeId=$('.mui-active').attr("data")  
        var code=getQueryString("code");
        if(rechargeNumber==""){
            alert("请输入隐隐ID");
            return false;
        }
        /* var verifyIdUrl="http://localhost:8080/faint-service/f/weixin/verifyUserNumber?rechargeNumber="+rechargeNumber; */
        var verifyIdUrl="https://www.chujian.live/faint-service/f/weixin/verifyUserNumber?rechargeNumber="+rechargeNumber;
        if(anit.hasClass("anit")){
            anit.removeClass("anit");
        }else{
            anit.addClass("anit");
            $.get(verifyIdUrl,function(data){
                if(data=="true"){
                    if(code){
                        var url="https://www.chujian.live/faint-service/f/weixin/goldOrders?code="+code+"&rechargeNumber="+rechargeNumber+"&rechargeId="+rechargeId;
                         /* var url="http://localhost:8080/faint-service/f/weixin/goldOrders?code="+code+"&rechargeNumber="+rechargeNumber+"&rechargeId="+rechargeId; */
                          $.get(url,function(result) {
                              var appId = result.appId;
                              var    timeStamp = result.timeStamp;
                              var nonceStr = result.nonceStr;
                              var package = result.package;
                              var    signType = result.signType;
                              var    paySign = result.paySign;
                                if (typeof WeixinJSBridge == "undefined") {
                                    if (document.addEventListener) {
                                        document.addEventListener('WeixinJSBridgeReady',onBridgeReady(appId,timeStamp,nonceStr,package,paySign), false);
                                    } else if (document.attachEvent) {
                                        document.attachEvent('WeixinJSBridgeReady',onBridgeReady(appId,timeStamp,nonceStr,package,paySign));
                                        document.attachEvent('onWeixinJSBridgeReady',onBridgeReady(appId,timeStamp,nonceStr,package,paySign));
                                    }
                                } else {
                                    onBridgeReady(appId,timeStamp,nonceStr,package,paySign);
                                }
                        });
                        } else {
                            alert("服务器错误");
                        }
                }else{
                    alert("用户不存在");
                }
            });    
        }
        
    }
        function onBridgeReady(appId,timeStamp,nonceStr,package,paySign){
              WeixinJSBridge.invoke( 'getBrandWCPayRequest', {
                  "appId":appId,     //公众号名称,由商户传入     
                  "timeStamp":timeStamp,         //时间戳,自1970年以来的秒数     
                  "nonceStr":nonceStr, //随机串     
                  "package":package,     
                  "signType":"MD5",         //微信签名方式:     
                  "paySign":paySign //微信签名
               },
               function(res){      
                   if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                       //支付成功后跳转的页面
                      location.href="https://www.chujian.live/faint-service/static/h5/success.html"
                   }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
                       alert("您已取消支付");
                   }else if(res.err_msg == "get_brand_wcpay_request:fail"){
                       alert("支付失败,请稍后再试");
                       WeixinJSBridge.call('closeWindow');
                   } //使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
         });   
        }

</script>
</html>

到这里呢,是不是觉得支付宝所有的支付都很简单

展开阅读全文

没有更多推荐了,返回首页