Java教程

支付宝支付

本文主要是介绍支付宝支付,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

将下载的文件放在 public/plugins/alipay

在 config 支付方法

'pay_type' => [
    'alipay' => ['pay_code'=>'alipay', 'pay_name'=>'支付宝', 'logo'=>'/static/home/img/_/pay2.jpg'],
    'wechat' => ['pay_code'=>'wechat', 'pay_name'=>'微信支付', 'logo'=>'/static/home/img/_/pay3.jpg'],
    'union' => ['pay_code'=>'union', 'pay_name'=>'银联', 'logo'=>'/static/home/img/_/pay4.jpg'],
],

html页面
<form id="orderForm" action="{:url('home/order/save')}" method="post" style="display: none;">
   <input type="hidden" name="address_id" value="">
</form>
<script>
   $(function(){
      //封装函数 将选中的地址,放到页面右下角展示
      var show_address = function(element){
         //获取到选中的地址信息
         if(element){
            var li = $(element).closest('li');
         }else{
            var li = $('.addressInfo').find('.name.selected').closest('li');
         }
         var consignee_address = li.find('.consignee_address').html();
         var consignee_phone = li.find('.consignee_phone').html();
         var consignee_name = li.find('.consignee_name').html();
         //展示到页面右下角
         $('.fc-receiverInfo').html('寄送至:' + consignee_address +' 收货人:' + consignee_name + ' ' + consignee_phone);
      };
      show_address();

      //点击地址 切换右下角的地址
      $('.addressInfo').find('.name').click(function(){
         show_address(this);
      });

      //提交订单
      $('.submit').click(function(){
         //获取选中的收货地址id
         var address_id = $('.addressInfo').find('.name.selected').attr('address_id');
         //将地址id放到表单中
         $('input[name=address_id]').val(address_id);
         //提交表单
         $('#orderForm').submit();
      });
   });
</script>

订单提交到
    public function save(Request $request)
    {

//       生成订单
        $params = input();
        $address = Address::where('id', $params['address'])->find();
        $order_sn = time() . mt_rand(100000, 999999);
        $user_id = session('uid');


        $data = [
            'user_id' => $user_id,
            'order_sn' => $order_sn,
            'consignee' => $address['consignee'],
            'address' => $address['address'],
            'phone' => $address['phone'],
            'goods_price' => $params['tot'],

        ];
        $sku = SpecValue::all();


        Db::startTrans();
        try {
//            创建订单前 进行库存检测、
//            foreach ($sku as $v) {
//                // $v['number']  $v['goods_number']
//                if ($v['store_count'] > $params['number']) {
//                    //抛出异常 直接进入catch语法结构
//                    throw new \Exception('订单中包含库存不足的商品');
//                }
//            }

//            //向订单商品表添加多条数据
            $orderId = \app\goods\model\Order::addInfo($data);
            session('orderId', $orderId['id']);
            Db::commit();
            //展示选择支付方式页面 。。。
            $pay_type = config('pay_type');
            return view('pay', ['order_sn' => $order_sn, 'pay_type' => $pay_type, 'total_price' => $data['goods_price']]);
        } catch (\Exception $e) {
            //回滚事务
            \think\Db::rollback();
            //$msg = $e->getMessage();
            //$this->error($msg);
            $this->error('创建订单失败,请重试');
        }

    }

或
    public function save(){
        //接收参数
        $params = input();
        //参数检测
        $validate = $this->validate($params, [
            'address_id' => 'require|integer|gt:0'
        ]);
        if($validate !== true){
            $this->error($validate);
        }
        //组装订单表数据 添加一条
        //查询收货地址
        $address = \app\common\model\Address::find($params['address_id']);
        if(!$address){
            $this->error('请重新选择收货地址');
        }
        //订单编号
        $order_sn = time() . mt_rand(100000, 999999);
        $user_id = session('user_info.id');
        //查询结算的商品(选中的购物记录以及商品和SKU信息)
        $res = \app\home\logic\OrderLogic::getCartDataWithGoods();
        //$res['cart_data']  $res['total_number'] $res['total_price']
        $order_data = [
            'user_id' => $user_id,
            'order_sn' => $order_sn,
            'consignee' => $address['consignee'],
            'address' => $address['area'] . $address['address'],
            'phone' => $address['phone'],
            'goods_price' => $res['total_price'], //商品总价
            'shipping_price' => 0,//邮费
            'coupon_price' => 0,//优惠金额
            'order_amount' => $res['total_price'],//应付金额=商品总价+邮费-优惠金额
            'total_amount' => $res['total_price'],//订单总金额=商品总价+邮费
        ];
        //开启事务
        \think\Db::startTrans();
        try{
            //创建订单前 进行库存检测
            foreach($res['cart_data'] as $v){
                // $v['number']  $v['goods_number']
                if($v['number'] > $v['goods_number']){
                    //抛出异常 直接进入catch语法结构
                    throw new \Exception('订单中包含库存不足的商品');
                }
            }
            $order = \app\common\model\Order::create($order_data);
//            //向订单商品表添加多条数据
//            $order_goods_data = [];
//            foreach($res['cart_data'] as $v){
//                $row = [
//                    'order_id' => $order['id'],
//                    'goods_id' => $v['goods_id'],
//                    'spec_goods_id' => $v['spec_goods_id'],
//                    'number' => $v['number'],
//                    'goods_name' => $v['goods_name'],
//                    'goods_logo' => $v['goods_logo'],
//                    'goods_price' => $v['goods_price'],
//                    'spec_value_names' => $v['value_names'],
//                ];
//                $order_goods_data[] = $row;
//            }
//            //批量添加
//            $model = new \app\common\model\OrderGoods();
//            $model->saveAll($order_goods_data);
//            //从购物车表删除对应数据
//            //\app\common\model\Cart::where(['user_id' => $user_id, 'is_selected'=>1])->delete();
//            //\app\common\model\Cart::where('user_id',$user_id)->where('is_selected',1)->delete();
//            //库存预扣减(冻结库存)
//            $spec_goods = [];
//            $goods = [];
//            foreach($res['cart_data'] as $v){
//                //判断是否有SKU 有则修改SKU表,无则修改商品表
//                if($v['spec_goods_id']){
//                    //修改SKU表  购买数量$v['number']  库存$v['goods_number']  冻结$v['frozen_number']
//                    $row = [
//                        'id'=>$v['spec_goods_id'],
//                        'store_count' => $v['goods_number'] - $v['number'],
//                        'store_frozen' => $v['frozen_number'] + $v['number']
//                    ];
//                    $spec_goods[] = $row;
//                }else{
//                    //修改商品表  购买数量$v['number']  库存$v['goods_number']  冻结$v['frozen_number']
//                    $row = [
//                        'id'=>$v['goods_id'],
//                        'goods_number' => $v['goods_number'] - $v['number'],
//                        'frozen_number' => $v['frozen_number'] + $v['number']
//                    ];
//                    $goods[] = $row;
//                }
//            }
//            //批量修改库存
//            $sku_model = new \app\common\model\SpecGoods();
//            $sku_model->saveAll($spec_goods);
//            $goods_model = new \app\common\model\Goods();
//            $goods_model->saveAll($goods);
//            //提交事务
            \think\Db::commit();
            //展示选择支付方式页面 。。。
            $pay_type = config('pay_type');
            return view('pay', ['order_sn' => $order_sn, 'pay_type'=>$pay_type, 'total_price'=>$res['total_price']]);
        }catch (\Exception $e){
            //回滚事务
            \think\Db::rollback();
            //$msg = $e->getMessage();
            //$this->error($msg);
            $this->error('创建订单失败,请重试');
        }
    }
<title>支付页</title>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/home/css/pages-pay.css" />
<div class="cart py-container">
    <!--主内容-->
    <div class="checkout py-container  pay">
        <div class="checkout-tit">
            <h4 class="tit-txt"><span class="success-icon"></span><span  class="success-info">订单提交成功,请您及时付款,以便尽快为您发货~~</span></h4>
            <div class="paymark">
                <span class="fl">请您在提交订单<em class="orange time">30分钟</em>之内完成支付,超时订单会自动取消。订单号:<em>{$order_sn}</em></span>
                <span class="fr"><em class="sui-lead">应付金额:</em><em  class="orange money">¥{$total_price}</em></span>
            </div>
        </div>

        <!--<div class="check-info">
            <h4>重要说明:</h4>
            <ol>
                <li>品优购商城支付平台目前支持<span class="zfb">支付宝</span>支付方式。</li>
                <li>其它支付渠道正在调试中,敬请期待。</li>
                <li>为了保证您的购物支付流程顺利完成,请保存以下支付宝信息。</li>
            </ol>
            <h4>支付宝账户信息:(很重要,<span class="save">请保存!!!</span>)</h4>
            <ul>
                <li>支付帐号:duqthf1038@sandbox.com</li>
                <li>密码:111111</li>
                <li>支付密码:111111</li>
            </ul>
        </div>-->

        <!--需增加的代码开始-->
        <div class="qrpay">
            <div class="step-tit">
                <h5>扫码付(支持支付宝、微信)</h5>
            </div>

        </div>
        <!--需增加的代码结束-->

        <div class="checkout-steps">
            <!--收件人信息-->
            <div class="step-tit">
                <h5>支付平台</h5>
            </div>
            <div class="step-cont">
                <ul class="payType">
                    {foreach $pay_type as $v}
                    <li class="" pay_code="{$v.pay_code}" {if($v.pay_code == 'alipay')}style="border: 2px solid rgb(228, 57, 60);"{/if}><img src="{$v.logo}"></li>
                    {/foreach}

                </ul>

            </div>
            <div class="hr"></div>

            <!--支付和送货-->
            <!--<div class="payshipInfo">
                <div class="step-tit">
                    <h5>支付网银</h5>
                </div>
                <div class="step-cont">
                    <ul class="payType">
                        <li><img src="/static/home/img/_/pay10.jpg"></li>
                        <li><img src="/static/home/img/_/pay11.jpg"></li>
                        <li><img src="/static/home/img/_/pay12.jpg"></li>
                        <li><img src="/static/home/img/_/pay13.jpg"></li>
                        <li><img src="/static/home/img/_/pay14.jpg"></li>
                        <li><img src="/static/home/img/_/pay15.jpg"></li>
                        <li><img src="/static/home/img/_/pay16.jpg"></li>
                        <li><img src="/static/home/img/_/pay17.jpg"></li>
                        <li><img src="/static/home/img/_/pay18.jpg"></li>
                        <li><img src="/static/home/img/_/pay19.jpg"></li>
                        <li><img src="/static/home/img/_/pay20.jpg"></li>
                        <li><img src="/static/home/img/_/pay21.jpg"></li>
                        <li><img src="/static/home/img/_/pay22.jpg"></li>

                    </ul>
                </div>
                <div class="hr"></div>
            </div>-->

            <div class="submit sui-text-center">

                <button class="btn"> 立即支付</button>
            </div>
            <!--<div class="otherpay">
                <div class="step-tit">
                    <h5>其他支付方式</h5>
                </div>
                <div class="step-cont">
                    <span><a href="weixinpay.html" target="_blank">微信支付</a></span>
                    <span>中国银联</span>
                </div>
            </div>-->
        </div>
    </div>

</div>
<form id="payForm" action="/order/pay" method="post">
    <input type="hidden" name="order_sn" value="{$order_sn}">
    <input type="hidden" name="pay_code" value="">
</form>
<script type="text/javascript">


    $(function(){
        $("ul.payType li").click(function(){
            $(this).css("border","2px solid #E4393C").siblings().css("border-color","#ddd");
        });

        //去支付
        $('.submit').click(function(){
            //获取选择的支付方式
            var pay_code = '';
            $('.payType li').each(function(i,v){
                //i是下标,v是li标签
                //console.log($(v).css('border-color'));
                if($(v).css('border-color') == 'rgb(228, 57, 60)'){
                    //console.log($(v).attr('pay_code'));
                    pay_code = $(v).attr('pay_code');
                }
            });
            //将支付方式pay_code放到表单中
            $('input[name=pay_code]').val(pay_code);
            //发送请求 表单提交
            $('#payForm').submit();
        })
    })
</script>
<script>
    $(function(){
        //轮询, 查询支付状态
        var order_sn = "{$order_sn}";
        var timer = setInterval(function(){
            $.ajax({
                "url":"{:url('home/order/status')}",
                "type":"post",
                "data":"order_sn=" + order_sn,
                "dataType":"json",
                "success":function(res){
                    if(res.code == 200 && res.data == 1){
                        clearInterval(timer);
                        location.href = "{:url('home/order/payresult')}?order_sn=" + order_sn;
                    }
                }
            });
        }, 1000);
    })
</script>


支付控制器

//支付
    public function pay()
    {
        $params = input();

        $validate = Loader::validate('Order');

        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

//        根据订单号查询订单是否存在

        $order = \app\goods\model\Order::where('order_sn', $params['order_sn'])->find();

        if (!$order) {
            $this->error('订单不存在');
        }
        //        //将选择的支付方式,修改到订单表
        $pay_type = config('pay_type');
        $order->pay_code = $params['pay_code'];
        //$order->pay_name = config('pay_type.' . $params['pay_code'])['pay_name'];
        $order->pay_name = $pay_type[$params['pay_code']]['pay_name'];
        $order->save();

//        print_r($order);die();
//        print_r($money);
                //默认 支付宝
                echo "<form id='alipayment' action='/plugins/alipay/pagepay/pagepay.php' method='post' style='display:none'>
    <input id='WIDout_trade_no' name='WIDout_trade_no' value='{$order['order_sn']}'/>
    <input id='WIDsubject' name='WIDsubject' value='品优购订单' />
    <input id='WIDtotal_amount' name='WIDtotal_amount' value='{$order['goods_price']}'/>
    <input id='WIDbody' name='WIDbody' value='品优购订单,测试订单,你付款了我也不发货' />
</form><script>document.getElementById('alipayment').submit();</script>";

/plugins/alipay/pagepay/pagepay.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>支付</title>
</head>
<?php
require_once dirname(dirname(__FILE__)).'/config.php';
require_once dirname(__FILE__).'/service/AlipayTradeService.php';
require_once dirname(__FILE__).'/buildermodel/AlipayTradePagePayContentBuilder.php';

    //商户订单号,商户网站订单系统中唯一订单号,必填
    $out_trade_no = trim($_POST['WIDout_trade_no']);

    //订单名称,必填
    $subject = trim($_POST['WIDsubject']);

    //付款金额,必填
    $total_amount = trim($_POST['WIDtotal_amount']);

    //商品描述,可空
    $body = trim($_POST['WIDbody']);

   //构造参数
   $payRequestBuilder = new AlipayTradePagePayContentBuilder();
   $payRequestBuilder->setBody($body);
   $payRequestBuilder->setSubject($subject);
   $payRequestBuilder->setTotalAmount($total_amount);
   $payRequestBuilder->setOutTradeNo($out_trade_no);

   $aop = new AlipayTradeService($config);

   /**
    * pagePay 电脑网站支付请求
    * @param $builder 业务参数,使用buildmodel中的对象生成。
    * @param $return_url 同步跳转地址,公网可以访问
    * @param $notify_url 异步通知地址,公网可以访问
    * @return $response 支付宝返回的信息
   */
   $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

   //输出表单
   var_dump($response);
?>
</body>
</html>

控制器 回调

function callback(){
    //参考/plugins/alipay/return_url.php
    //接收参数
    $params = input();
    //参数检测(签名验证)  接收到的参数 和 支付宝传递的参数 是否发生改变
    require_once("./plugins/alipay/config.php");
    require_once './plugins/alipay/pagepay/service/AlipayTradeService.php';
    $alipaySevice = new \AlipayTradeService($config);
    $result = $alipaySevice->check($params);
    if($result){
        //验签成功
        $order_sn = $params['out_trade_no'];
        $order = \app\goods\model\Order::where('order_sn', $order_sn)->find();
        //展示结果
        return view('paysuccess', ['pay_name' => '支付宝', 'order_amount'=>$params['total_amount'], 'order' => $order]);
    }else{
        //验签失败
        //展示结果
        return view('payfail', ['msg' => '支付失败']);
    }
}


成功页面

<title>支付页-成功</title>

   <link rel="stylesheet" type="text/css" href="/static/home/css/pages-paysuccess.css" />

<div class="cart py-container">
   <!--主内容-->
   <div class="paysuccess">
      <div class="success">
         <h3><img src="/static/home/img/_/right.png" width="48" height="48"> 恭喜您,支付成功啦!</h3>
         <div class="paydetail">
         <p>支付方式:{$pay_name}</p>
         <p>支付金额:¥{$order_amount}元</p>
         <p class="button"><a href="javascript:;" class="sui-btn btn-xlarge btn-danger">查看订单</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="{:url('home/index/index')}" class="sui-btn btn-xlarge ">继续购物</a></p>
          </div>
      </div>
      
   </div>
</div>

失败页面

<title>支付页-失败</title>

   <link rel="stylesheet" type="text/css" href="/static/home/css/pages-payfail.css" />

<div class="cart py-container">
   <!--主内容-->
   <div class="payfail">
      <div class="fail">
         <h3><img src="/static/home/img/_/fail.png" width="48" height="48"> 支付失败,请稍后再试</h3>
         <div class="fail-text">
         <p>失败原因:{$msg}</p>
         <p>您可以先去 <a href="{:url('home/index/index')}" target="_blank">品优购首页</a> 逛逛</p>
         <p class="button"><a href="javascript:;" class="sui-btn btn-xlarge btn-danger">重新支付</a></p>
          </div>
      </div>
      
   </div>
</div>
 

















 

这篇关于支付宝支付的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!