您的位置:首页 > 移动开发 > 微信开发

浅谈购物车之支付宝(微信)支付功能

2018-03-16 08:48 507 查看
       今天给大家介绍一个专门培养复合型人才的高大上平台:《融e学网》→

www.i-ronge.com

,里面涵盖经,管,法,国学,易经,面试,体育,葡萄酒等领域的诸多课程,课程内容都是请全国大咖专门录制,不满足于现状想要寻求突破的小伙伴不要错过这个平台哦。。。
首先,我们在url地址栏输入:www.i-ronge.com



随便点击一门课程,比如《管理者哲学思维训练》



点击“购买课程”,加入购物车,选择支付宝支付



点击“提交订单”


打开支付宝输入密码即可付款成功。今天,我们就“选课→购物车→下单→支付宝成功支付”这一流程探讨哈基本的数据库设计及后台代码的实现,下面,小伙伴们就跟着我走吧!!!首先,我们要选课所以我们需要一张课程表,用mysql数据库建立一张课程表edu_courseCREATE TABLE `edu_course` (
  `course_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '课程主键',
  `course_name` varchar(256) DEFAULT '' COMMENT '课程名称',
  `is_avaliable` int(10) DEFAULT '0' COMMENT '1正常2删除',
  `subject_id` int(11) DEFAULT '0' COMMENT '课程专业ID',
  `subject_link` varchar(256) DEFAULT NULL COMMENT '课程专业链',
  `add_time` timestamp NULL DEFAULT NULL COMMENT '添加时间',
  `source_price` decimal(10,2) DEFAULT '0.00' COMMENT '课程原价格(只显示)',
  `current_price` decimal(10,2) DEFAULT '0.00' COMMENT '课程销售价格(实际支付价格)设置为0则可免费观看',
  `title` varchar(512) DEFAULT '' COMMENT '课程简介',
  `context` longtext COMMENT '课程详情',
  `lession_num` int(11) DEFAULT '0' COMMENT '总课时',
  `logo` varchar(256) DEFAULT '' COMMENT '图片路径',
  `update_time` timestamp NULL DEFAULT NULL COMMENT '最后更新时间',
  `real_buycount` int(11) DEFAULT '0' COMMENT '真实购买数量',
  `real_viewcount` int(11) DEFAULT '0' COMMENT '真实浏览数量',
  `end_time` timestamp NULL DEFAULT NULL COMMENT '有效结束时间',
  `losetype` int(2) DEFAULT '0' COMMENT '有效期类型,0:到期时间,1:按天数',
  `lose_time` varchar(256) DEFAULT NULL COMMENT '有效期:商品订单过期时间点',
  `sell_type` varchar(16) DEFAULT 'COURSE' COMMENT '类型:COURSE(课程)、CLASS(班级)',
  `sequence` int(11) DEFAULT '0' COMMENT '序列',
  `live_begin_time` datetime DEFAULT NULL COMMENT '直播开始时间',
  `live_end_time` datetime DEFAULT NULL COMMENT '直播结束时间',
  `admin_id` int(11) DEFAULT '0' COMMENT '创建课程的后台用户id',
  `fake_buycount` int(11) DEFAULT '0' COMMENT '虚拟购买数',
  `fake_viewcount` int(11) DEFAULT '0' COMMENT '虚拟浏览数',
  `start_time` datetime DEFAULT NULL COMMENT '开始时间(可拓展公用)',
  `close_time` datetime DEFAULT NULL COMMENT '结束时间(可拓展公用)',
  `head_teacher_id` varchar(256) DEFAULT NULL COMMENT '班主任id(逗号分隔)',
  `course_background` varchar(512) DEFAULT '' COMMENT '课程背景',
  `teaching_aim` varchar(512) DEFAULT '' COMMENT '教学目标',
  `affiliated_institutions` varchar(64) DEFAULT '' COMMENT '所属院校',
  `credit` float(11,0) DEFAULT NULL COMMENT '学分',
  `exam_time` datetime DEFAULT NULL COMMENT '考试时间',
  `institute` varchar(64) DEFAULT '' COMMENT '学院',
  `course_properties` varchar(64) DEFAULT '' COMMENT '课程属性',
  `uploader_id` int(11) DEFAULT '0' COMMENT '上传者id',
  `state` int(11) DEFAULT '0' COMMENT '课程审核状态(0:保利威士上传,1:审核成功,2:审核失败;3:待审核)',
  `conscientiousPerson` varchar(256) DEFAULT '' COMMENT '负责人',
  `auditorId` int(11) DEFAULT '0' COMMENT ' 审核者id',
  `exam_begin_time` datetime DEFAULT NULL COMMENT '考试开始时间',
  `exam_end_time` datetime DEFAULT NULL COMMENT '考试结束时间',
  `sort` int(11) DEFAULT '0' COMMENT '排序',
  `type_sort` int(11) DEFAULT '0' COMMENT '类型排序',
  `product_id` int(11) DEFAULT '0' COMMENT '产品id',
  `product_link` varchar(256) DEFAULT NULL COMMENT '产品链接',
  `product_sort` int(11) DEFAULT NULL,
  `quota_of_people` int(11) DEFAULT '0' COMMENT '总名额',
  `used_quota` int(11) DEFAULT '0' COMMENT '已使用名额',
  `owned_enterprises` int(11) DEFAULT '0' COMMENT '所属高校',
  `stick_status` int(11) DEFAULT '1' COMMENT '置顶状态[1:(默认);2:工作人员可以直接进行操作的;3:普通的(交费);]',
  `stick_begin_time` datetime DEFAULT NULL COMMENT '置顶开始时间',
  `stick_end_time` datetime DEFAULT NULL COMMENT '置顶结束时间',
  `stick_price` decimal(10,2) DEFAULT NULL COMMENT '置顶价格',
  PRIMARY KEY (`course_id`)

) ENGINE=InnoDB AUTO_INCREMENT=334 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='课程表';然后我们要把课程加入购物车中,所以,我们要建一张购物车表:edu_shopcarCREATE TABLE `edu_shopcart` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `goodsid` int(10) unsigned NOT NULL COMMENT '商品id',
  `userid` int(10) unsigned NOT NULL COMMENT '用户id',
  `type` int(11) NOT NULL DEFAULT '1' COMMENT '类型1课程2套餐3:置顶',
  `add_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '加增时间',
  PRIMARY KEY (`id`),
  KEY `userid` (`userid`)

) ENGINE=InnoDB AUTO_INCREMENT=835 DEFAULT CHARSET=utf8 COMMENT='购物车';
加入购物车后我们需要下单,这时我们就需要两张表,一张订单表:edu_orders,一张订单详情表:edu_trxorder_detail
CREATE TABLE `edu_orders` (
  `ORDER_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单ID',
  `USER_ID` int(11) DEFAULT '0' COMMENT '用户ID',
  `ORDER_NO` varchar(50) DEFAULT NULL COMMENT '订单号',
  `SUM_MONEY` decimal(10,2) DEFAULT '0.00' COMMENT '订单总金额',
  `STATES` varchar(10) DEFAULT NULL COMMENT '订单状态 SUCCESS已支付 INIT未支付  CANCEL已取消',
  `CREATE_TIME` timestamp NULL DEFAULT NULL COMMENT '订单创建时间',
  `PAY_TIME` timestamp NULL DEFAULT NULL COMMENT '订单支付时间',
  `SYS_USER_ID` int(11) DEFAULT '0' COMMENT '审核用户ID',
  `PAY_TYPE` varchar(50) DEFAULT 'ALIPAY' COMMENT '支付类型',
  `req_channel` varchar(20) DEFAULT NULL COMMENT '请求渠道(WEB,APP)',
  `description` varchar(500) DEFAULT NULL COMMENT '备用描述',
  `version` int(11) DEFAULT NULL COMMENT '乐观锁版本号',
  `req_ip` varchar(15) DEFAULT NULL COMMENT '客户端IP',
  `order_amount` decimal(10,2) DEFAULT NULL COMMENT '订单原始金额',
  `coupon_amount` decimal(10,2) DEFAULT NULL COMMENT '优惠券金额',
  `couponCode_id` int(11) DEFAULT NULL COMMENT '优惠券编码id',
  `refund_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
  `out_trade_no` varchar(200) DEFAULT NULL COMMENT '第三方支付商户订单号',
  PRIMARY KEY (`ORDER_ID`),
  KEY `order_no` (`ORDER_NO`)

) ENGINE=InnoDB AUTO_INCREMENT=31652 DEFAULT CHARSET=utf8 COMMENT='课程订单表';
CREATE TABLE `edu_trxorder_detail` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '用户id',
  `course_id` int(11) unsigned NOT NULL COMMENT '相关联的课程id/套餐id(前台快照)',
  `trxorder_id` int(11) NOT NULL DEFAULT '0' COMMENT '交易订单ID',
  `membertype` tinyint(3) DEFAULT '0' COMMENT '会员观看类型(前台快照)',
  `losetype` int(3) NOT NULL DEFAULT '0' COMMENT '有效期类型(前台快照)',
  `lose_abs_time` datetime DEFAULT NULL COMMENT '订单过期时间段(前台快照)',
  `lose_time` varchar(255) DEFAULT NULL COMMENT '订单过期时间点(前台快照)',
  `auth_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '课程过期时间',
  `create_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '下单时间',
  `pay_time` datetime DEFAULT NULL COMMENT '支付成功时间',
  `source_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '原价格(前台快照)',
  `coupon_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '优惠价格',
  `current_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '销售价格(前台快照)',
  `course_name` varchar(255) NOT NULL DEFAULT '' COMMENT '课程名称(前台goods快照)',
  `trx_status` char(15) NOT NULL DEFAULT '' COMMENT '订单状态(前台goods快照)',
  `auth_status` char(10) NOT NULL DEFAULT '' COMMENT '课程状态(INIT,SUCCESS,REFUND,CLOSED,LOSED)',
  `request_id` varchar(50) NOT NULL DEFAULT '' COMMENT '订单请求号',
  `description` varchar(50) NOT NULL DEFAULT '' COMMENT '描述',
  `version` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '乐观锁版本号',
  `last_update_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '最后更新时间',
  `remind_status` varchar(255) DEFAULT 'INIT' COMMENT '过期是否提醒 INIT 未提醒 ALREADY 已提醒',
  `mustLook` int(1) DEFAULT '0' COMMENT '1是防刷,进度条不可拖动,0是可拖动',
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `trxorder_id` (`trxorder_id`),
  KEY `IDX_REQUEST_ID` (`request_id`)

) ENGINE=InnoDB AUTO_INCREMENT=32374 DEFAULT CHARSET=utf8 COMMENT='流水表';
到这里为止,我们数据库已建立完毕,下面我们开始写后台代码,我这里用的是ssm架构
第一,创建所有的实体类
@Data
@EqualsAndHashCode(callSuper = false)
public class QueryCourse implements Serializable {

private static final long serialVersionUID = 4550896941810655734L;
private Long courseId;
private int subjectId;
private String subjectLink;
private String courseName;
private int isavaliable;
private int teacherId;
private int count;
private String order;
private String isFree;// 查询免费课程
private String sellType;// 课程类型:COURSE(课程) LIVE(直播) PACKAGE(套餐)
private String sellType_cou_live;// 用于查询课程类型:COURSE(课程) + LIVE(直播)
private int adminId;// 创建课程的后台用户ids
private String isOverdue;// 查询过期课程
private int productId;// 产品id
private int ownedEnterprises;//所属企业

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date beginCreateTime;// 查询 开始添加时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

private Date endCreateTime;// 查询 结束添加时间
}

@Data
@EqualsAndHashCode(callSuper = false)
public class Shopcart implements Serializable {
    private static final long serialVersionUID = 6757060331190184782L;
    private Long id;
    private Long goodsid;// 商品id
    private Long userid;
    private Long type;//1课程 2套餐(备用) 3课程置顶
    private java.util.Date addTime;
    private Course course;

}
@Data
public class Order implements Serializable{
private static final long serialVersionUID = 7687324559966427231L;
/**订单ID*/
private int orderId;
/**购买用户ID*/
private int userId;
/**订单号*/
private String orderNo;
/**订单总金额*/
private BigDecimal sumMoney;
/**订单状态  SUCCESS已支付 INIT未支付 CANCEL已取消*/
private String states;
/**订单创建时间*/
private Date createTime;
/**订单支付时间*/
private Date payTime;
/**后台审核用户ID*/
private int sysUserId;
/**支付类型 ALIPAY支付宝  FREE免费赠送,后台赠送  */
private String payType;
/**请求渠道(WEB,APP)*/
private String reqChannel;
private String description;//备用描述
private Long version=0L;//乐观锁版本号
private String reqIp;//客户端IP
private BigDecimal orderAmount;//订单原始金额
private BigDecimal couponAmount;//优惠券金额
private Long couponCodeId=0L;//优惠券编码id
private BigDecimal refundAmount;//退款金额
private String outTradeNo;//第三方支付商户订单号

/**课程名称*/
private String courseName;
/**课程标题*/
private String courseTitle;
/**课程图片*/
private String courseLogo;
/**查询数*/
private int limitNum;
/**用户邮箱*/
private String email;
/**用户姓名*/
private String userName;
/**头像*/
private String picImg;

/**订单创建时间 格式化显示**/
private String createTimeFormat;
/**订单流水课程**/
private java.util.List<TrxorderDetailDTO> trxorderDetailList;

private String loginName;//审核人账号

//格式化显示时间
public void setCreateTime(Date date){
this.createTime=date;
this.createTimeFormat=getModelDate(this.getCreateTime());
}

public String getModelDate(Date oldDate) {
if (oldDate!=null) {
Date newDate = new Date();
long second = (newDate.getTime() - oldDate.getTime()) / 1000L;
if (second <= 60L)
return second + "秒前";
if ((60L < second) && (second <= 3600L)) {
second /= 60L;
return second + "分钟前";
}
if ((3600L < second) && (second <= 86400L)) {
second = second / 60L / 60L;
return second + "小时前";
}
if ((86400L < second) && (second <= 864000L)) {
String formatDate = DateUtils.formatDate(oldDate, "HH:mm");
second = second / 60L / 60L / 24L;

return second + "天前";
}
return DateUtils.formatDate(oldDate, "yyyy-MM-dd HH:mm");
}
return "";
}

}
@Data
@EqualsAndHashCode(callSuper = false)
public class TrxorderDetail implements Serializable{
    private static final long serialVersionUID = 7081379317366445288L;
    private Long id;
    private Long userId;//用户id
    private Long courseId;//相关联的课程id(前台快照)
    private Long trxorderId;//交易订单ID
    private Long membertype;//会员观看类型(前台快照)
    private int losetype;//有效期类型(前台快照)
    private java.util.Date loseAbsTime;//订单过期时间段(前台快照)
    private String loseTime;//订单过期时间点(前台快照)
    private java.util.Date authTime;//课程过期时间
    private java.util.Date createTime;//下单时间
    private java.util.Date payTime;//支付成功时间
    private java.math.BigDecimal sourcePrice;//原价格(前台快照)
    private java.math.BigDecimal currentPrice;//销售价格(前台快照)
    private String courseName;//课程名称(前台goods快照)
    private String trxStatus;//订单状态(前台goods快照)
    private String authStatus;//课程状态(INIT,SUCCESS,REFUND,CLOSED,LOSED)
    private String requestId;//订单请求号
    private String description;//描述
    private Long version=1L;//乐观锁版本号
    private java.util.Date lastUpdateTime;//最后更新时间
    private List<Teacher> teacherList;//最后更新时间
    private int mustLook;//  默认0 ,能拖动视频进度条 1为不能快进.

    //辅助属性
    /**课程标题*/
    private String courseTitle;
    /**课程图片*/
    private String courseLogo;
    private int playFromType;

}
第一步:查询课程并显示
<select id="queryCourse" parameterType="QueryCourse" resultMap="CourseDtoResult">
SELECT
<include refid="edu_course_columns" />
FROM EDU_COURSE
<where>
<if test="isavaliable>0">
EDU_COURSE.IS_AVALIABLE=#{isavaliable}
</if>
<if test="sellType !=null and sellType != ''">
AND EDU_COURSE.SELL_TYPE = #{sellType}
</if>
<if test="isOverdue=='true'"><!-- 查询未过期课程 -->
AND (EDU_COURSE.END_TIME IS NULL OR EDU_COURSE.END_TIME>NOW())
</if>
<if test="productId>0">
AND EDU_COURSE.PRODUCT_LINK LIKE
CONCAT('%,',#{productId},',%')
</if>
</where>
<if test="order=='FOLLOW'">
ORDER BY
(EDU_COURSE.real_viewcount+EDU_COURSE.fake_viewcount) DESC
</if>
<if test="order=='NEW'">
ORDER BY edu_course.stick_status
desc,edu_course.stick_begin_time
</if>
<if test="order=='BUY'">
ORDER BY
(EDU_COURSE.real_buycount+EDU_COURSE.fake_buycount) DESC
</if>
<if test="order=='PRODUCTSORT'">
ORDER BY EDU_COURSE.product_sort DESC
</if>
<if test="count>0 and count!=null">
LIMIT #{count}
</if>
</select>

// 所有产品分类课程
List<Product> productsList = (List<Product>) CacheUtil
.get(CacheConstans.INDEX_PRODUCT_CLASSIFY);
if (productsList == null || productsList.size() == 0) {
QueryProduct queryProduct = new QueryProduct();
queryProduct.setParentId(0);
productsList = productService.getAllProductList(queryProduct);
CacheUtil.set(CacheConstans.INDEX_PRODUCT_CLASSIFY,
productsList, CacheConstans.RECOMMEND_COURSE_TIME);// 缓存一小时
}
Iterator<Product> it = productsList.iterator();
while (it.hasNext()) {
Product product = it.next();
int pId = product.getId();
try {
QueryCourse queryCourses = new QueryCourse();
queryCourses.setCount(4);// 只显示4条数据
queryCourses.setIsavaliable(1);// 只查询上架的
queryCourses.setSellType("COURSE");// 类型课程
queryCourses.setIsOverdue("true");// 查询未过期的
queryCourses.setOrder("PRODUCTSORT");
queryCourses.setProductId(pId);
List<CourseDto> courseProductClassifyList = courseService
.queryCourse(queryCourses);
product.setCourseProductClassifyList(courseProductClassifyList);
} catch (Exception e) {
logger.error(
"WebFrontController.courseProductClassifyList()--error",
e);
}
}
request.setAttribute("productsList", productsList);

<!-- 按产品分类显示开始 -->
<c:forEach var="products" items="${productsList}">
<div class="bg-fa -of">
<section class="container">
<header class="comm-title">
<div class="fr mt5 mr5">
<a href="/front/showcoulist?queryCourse.productId=${products.id}" title="" class="c-666 c-more"><img
src="/static/mooc_web/img/sl-dot.png" width="32" height="32"></a>
</div>
<h2 class="fl tac popover-main">
<span class="c-333">${products.productName}</span>
</h2>
<c:if test="${products.productName == '校园EMBA'}">
<div class="popover dn">
EMBA是国际商业领域成熟、成功的教育模式,是专门培养企业高级管理人员的教育项目。其特点在于知识的复合性、实操性、浓缩性。本培训项目借鉴该模式,将其引入校园,专门为非工商管理类大学生、研究生及职业人士定制化培养,让您手捧“专业文凭+就业证书”,顺利地走进您理想中的就业单位。
</div>
</c:if>
<div class="clear"></div>
</header>
<article class="comm-course-list">
<ul class="of clearfix">
<c:forEach var="courseNew"
items="${products.courseProductClassifyList}">
<li>
<div class="cc-l-wrap">
<section class="course-img">
<c:if test="${not empty courseNew.logo }">
<img xsrc="http://www.i-ronge.com${courseNew.logo }"
src="${ctx}/static/mooc_web/img/default-img.gif"
class="img-responsive" alt="${courseNew.courseName }">
</c:if>
<c:if test="${empty courseNew.logo }">
<img xsrc="static/mooc_web/img/default-img.gif"
src="${ctx}/static/mooc_web/img/default-img.gif"
class="img-responsive" alt="${courseNew.courseName }">
</c:if>
<div class="cc-mask">
<a href="${ctx}/front/couinfo/${courseNew.courseId}"
title="开始学习" class="comm-btn c-btn-1">开始学习</a>
</div>
</section>
<div class="cou-info-box">
<h3 class="hLh30 txtOf mt10">
<a href="${ctx}/front/couinfo/${courseNew.courseId}"
title="${courseNew.courseName }"
class="course-title fsize18 c-333">${courseNew.courseName }</a>
</h3>
<section class="mt10 clearfix of">
<span class="fl jgAttr c-ccc txtOf">
    <tt class="c-999 f-fM mr10 fsize14">${courseNew.pageViewcount }人浏览</tt> 
    <tt class="c-999 f-fM mr10 fsize14">${courseNew.pageBuycount }人购买</tt>|
<tt class="c-999 f-fM fsize14">共${courseNew.lessionNum }节课</tt>
</span>
</section>
<div>
<c:if test="${courseNew.currentPrice=='0.00' }">
<span class="jgTag green-bor"><tt
class="c-green fsize12 f-fM">免费</tt></span>
</c:if>
<c:if test="${courseNew.currentPrice!='0.00' }">
<span class="jgTag yellow-bor"><tt
class="c-yellow fsize12 f-fM">¥${courseNew.currentPrice }</tt></span>
</c:if>
</div>
</div>
</div>
</li>
</c:forEach>
</ul>
<div class="clear"></div>
</article>
</section>
</div>
</c:forEach>

<!-- 按产品分类显示结束 -->

加入购物车
/**
* 添加商品并跳转到购物车

* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "/shopcart", params = "command=addShopitem")
public String addShopcart(HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
String goodsId = request.getParameter("goodsid");// 商品id
String type = request.getParameter("type");// 类型1课程2套餐
if (StringUtils.isNotEmpty(goodsId) && StringUtils.isNotEmpty(type)) {
int userId = SingletonLoginUtils.getLoginUserId(request);
if (userId != 0) {
// 登录用户添加到数据库
shopcartService.addShopcart(Long.valueOf(goodsId),
Long.valueOf(type), Long.valueOf(userId));
} else {
// 从Cookie获取购物车信息
String shopJson = WebUtils.getCookie(request,
OrderConstans.SHOP_CART);
shopJson = shopcartService
.addTempShopcart(Long.valueOf(goodsId),
Long.valueOf(type), shopJson);
WebUtils.setCookie(response, OrderConstans.SHOP_CART,
shopJson, 1);
}
}
} catch (Exception e) {
logger.error("addShopcart error", e);
return setExceptionRequest(request, e);
}
return "redirect:/shopcart?command=queryShopCart";
}

/**
* 查询购物车(临时购物车,用户购物车)

* @param request
* @param response
* @return
*/
@RequestMapping(value = "/shopcart", params = "command=queryShopCart")
public String queryShopCart(HttpServletRequest request,
HttpServletResponse response) {
try {
// 用户登录查询用户优惠券
if (SingletonLoginUtils.getLoginUserId(request) != 0) {
// 获取用户购物车总价格
List<Shopcart> shopCartList = null;
// 总价格
BigDecimal totalMoney = new BigDecimal(0);
int userId = SingletonLoginUtils.getLoginUserId(request);
if (userId != 0) {
shopCartList = shopcartService.getShopcartList(
Long.valueOf(userId), 1l);
} else {
String json = WebUtils.getCookie(request,
OrderConstans.SHOP_CART);
shopCartList = shopcartService.getTempShopcartList(json);
}
if (ObjectUtils.isNotNull(shopCartList)) {
for (Shopcart sc : shopCartList) {
totalMoney = totalMoney.add(sc.getCourse()
.getCurrentPrice());
}
}
if ("ON".equals(CacheConstans.COUPON_IS_OPEN)
&& ObjectUtils.isNotNull(couponCodeService)) {
// 查询我的优惠券 查询可以使用 并且达到优惠券最低限额的优惠券
QueryCouponCode queryCouponCode = new QueryCouponCode();
queryCouponCode.setUserId(Long.valueOf(userId));
queryCouponCode.setLimitAmount(totalMoney);
queryCouponCode.setStatus(1);
queryCouponCode.setType(1);// 查询课程优惠券(非会员优惠券)
List<CouponCodeDTO> couponCodeList = couponCodeService
.queryCouponCodeByUser(queryCouponCode);
request.setAttribute("couponCodeList", couponCodeList);
}
}
} catch (Exception e) {
logger.error("ShopcartController.queryShopCart()--error", e);
setExceptionRequest(request, e);
}
return shopCart;

}

<div id="aCoursesList" class="bg-fa of">
<div class="container">
<section class="path-wrap txtOf hLh30">
<a class="c-999 fsize14" title="" href="${ctx }">首页</a>
\<span class="c-333 fsize14">购物车</span>
</section>
<article class="mt30">
<div class="mt30">
<header class=""><span class="fsize24 c-333">确认课程</span></header>

<dl class="c-order-list of" id="shopingcart">
                                       <dt>
        <ul class="c-o-head clearfix of">
<li class="c-head-li-16"><span>课程</span></li>
<li class="c-head-li-1"><span>标题</span></li>
<li class="c-head-li-2"><span>讲师</span></li>
<li class="c-head-li-3"><span>价格</span></li>
<li class="c-head-li-4"><span>操作</span></li>
</ul>
</dt>
<c:set var="totalMoney" value="0"></c:set>
<c:choose>
<c:when test="${not empty  shopcartList}">
<c:forEach items="${shopcartList }" var="sc">
<dd>
<ul class="c-o-tbody clearfix of">
<li class="c-head-li-16"><div class="c-o-t-img">
<c:choose>
<c:when test="${not empty sc.course.logo}">
<img src="<%=contextPath%>${sc.course.logo}" class="img-responsive">
</c:when>
<c:otherwise>
<img src="/static/mooc_web/img/default-img.gif" class="img-responsive">
</c:otherwise>
</c:choose>
</div></li>
<li class="c-head-li-36">
<div class="c-head-title">
<h6 class="unFw c-666"> ${sc.course.courseName}</h6>
<div class="mt10 u-order-desc">
<p class="c-999 txtOf"> ${sc.course.title}</p>
</div>
</div>
</li>
<li>
<div class="c-t-wz"><span class="c-666">
<c:forEach items="${sc.course.teacherList }" var="teacher">
${teacher.name} 
</c:forEach>
</span></div>
</li>
<li>
<div class="c-t-wz"><span class="c-666">¥${sc.course.currentPrice }</span></div>
</li>
<li>
<div class="c-t-wz"><a href="javascript:deleteid(${sc.id},${sc.goodsid },${sc.type})" class="c-666">取消</a></div>
<c:set var="totalMoney" value="${totalMoney+sc.course.currentPrice }"></c:set>
</li>
</ul>
</dd>
</c:forEach>
</c:when>
<c:otherwise>
<dd>
<section class="no-data-wrap"><em class="icon30 no-data-ico"> </em><span class="c-666 fsize14 ml10 vam">购物车为空,请先选购<a target="" href="${ctx}/front/showcoulist" title="课程" class="c-master ml5">课程</a>...</span></section>
</dd>
</c:otherwise>
</c:choose>
<div class="buyCom_price c-666 fr tar mt10 pr10">
<span>课程数量:<span class="fsize14 c-orange mr5" id="buyCount">${shopcartList.size()}</span>  </span>
课程金额:<span class="fsize14 c-orange mr5" id="div_totalMoney">¥${totalMoney }</span>
</div>

</dl>
</div>
<div  style="display: none;">
<!-- alipay参数 -->
<form action="${ctx }/order/bank" name="orderForm" id="orderForm" method="post" target="">
<input id="orderId" name="orderId" type="hidden" value=""/>
<input id="defaultbank" name="defaultbank" type="hidden" value=""/>
<input id="opendId" name="opendId" type="hidden" value=""/>
<input id="payType" name="payType" type="hidden" value="WEIXIN" />
<input id="typeOfPurchase" name="typeOfPurchase" type="hidden" value="1"/>
</form>
</div>
<!-- 优惠券编码 -->
<div  style="display: none;">
<input id="couponCodeHidden" type="hidden" value=""/>
</div>
<div class="mt30">
<header class=""><span class="fsize24 c-333">支付方式</span></header>
   <div class="">
<header class="c-p-title"><strong style="font-size:17px;margin:3px;">转账支付</strong></header>
<div class="" style="margin:3px;">
开户行:中国银行股份有限公司武汉东湖开发区支行<br/>
账号:559967874003
</div>
</div>
<div  class="" >
<header class="c-p-title"><strong style="font-size:17px;margin:3px;">优惠购买</strong></header>
<div class="" style="margin:3px;">
       加客服小E微信(17786424575),优惠购买。
</div>
</div>
<div class="c-pay-method">
<c:if test="${yibaoIsOpen=='ON'}">
<div  class="of">
<header class="c-p-title">网上银行</header>
<div class="buyB_payPlat">
<ul class="clearfix">
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="CEB-NET"> <img src="/static/mooc_web/img/buy/bank_ZGGDYH.png" alt="广大银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="ICBC-NET"><img src="/static/mooc_web/img/buy/bank_ZGGSYH.png" alt="中国工商银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="CCB-NET"><img src="/static/mooc_web/img/buy/bank_ZGJSYH.png" alt="中国建设银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="ABC-NET"><img src="/static/mooc_web/img/buy/bank_ZGNYYH.png" alt="中国农业银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="CMBCHINA-NET"><img src="/static/mooc_web/img/buy/bank_ZSYH.png" alt="招商银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="BOC-NET"><img src="/static/mooc_web/img/buy/bank_ZGYH.png" alt="中国银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="BOCO-NET"><img src="/static/mooc_web/img/buy/bank_JTYH.png" alt="中国交通银行"></label></li>
<li><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="POST-NET"><img src="/static/mooc_web/img/buy/bank_ZGYZCXYH.png" alt="中国邮政储蓄银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="CIB-NET"><img src="/static/mooc_web/img/buy/bank_XYYH.png" alt="兴业银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="CMBC-NET"><img src="/static/mooc_web/img/buy/bank_ZGMSYH.png" alt="中国民生银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="ECITIC-NET"><img src="/static/mooc_web/img/buy/bank_ZXYH.png" alt="中兴银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="PAB-NET"><img src="/static/mooc_web/img/buy/bank_PAYH.png" alt="平安银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="SDB-NET"><img src="/static/mooc_web/img/buy/bank_SZFZYH.png" alt="深圳发展银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="SHB-NET"><img src="/static/mooc_web/img/buy/bank_SHYH.png" alt="上海银行"></label></li>
<li class="buyB_payPlatNone"><label><input type="radio" onclick="checkbank('YEEPAY')" name="defaultbank" value="BJRCB-NET"><img src="/static/mooc_web/img/buy/bank_BJNSYH.png" alt="北京农商银行"></label></li>
</ul>
</div>
</div>
</c:if>
<div  class="of">
<header class="c-p-title">第三方支付</header>
<div class="buyB_payPlat">
<ul class="clearfix">
<c:if test="${weixinIsOpen=='ON' }">
<li><label><input type="radio" onclick="checkbank('WEIXIN')" checked="checked" name="weixin" value=""> <img alt="微信" src="/static/mooc_web/img/buy/buyB_pay_wx.jpg"> </label> </li>
</c:if>
<c:if test="${zhifubaoIsOpen=='ON' }">
<li> <label> <input type="radio" onclick="checkbank('ALIPAY')"  name="alipay" value=""> <img alt="支付宝" src="/static/mooc_web/img/buy/buyB_pay_kuaiqian3.jpg"> </label> </li>
</c:if>
<c:if test="${yibaoIsOpen=='ON'}">
<li>
<label><input type="radio" value="00" name="yeepay"  onclick="checkbank('YEEPAY')"   style="margin-top:5px;" />
<img src="/static/mooc_web/img/buy/buyB_pay_yibao.jpg" alt="易宝"  /></label></li>
</c:if>
</ul>
</div>
</div>
</div>
</div>
<div class="mt30">
<header class=""><span class="fsize24 c-333">结算信息</span></header>
<div class="c-pay-method c-p-m">
<div>
<c:if test="${couponIsOpen=='ON'}">
<div class="fl ml20">
<p class="fsize14 c-666">使用代金券可以抵消部分金额哦</p>
<div class="mt20 coupon-box clearfix">
<select id="queryCoupon" class="buyText01 fl" name="queryCouponCode.status" onchange="chooseCoupon(this)" style="width: 204px;">
<option value="">--选择我已有的优惠券--</option>
<c:forEach items="${couponCodeList}" var="coupon">
<option value="${coupon.couponCode}">
<c:if test="${coupon.type==1}">
<fmt:formatNumber value="${coupon.amount}" pattern="0.0"/>折
</c:if>
<c:if test="${coupon.type==2}">
¥${coupon.amount}
</c:if>
</option>
</c:forEach>
</select>
</div>
<div class="mt20 coupon-box clearfix">
<input class="buyText01 fl" type="text" id="couponCode" onkeyup="inputcode()" name="" placeholder="请输入优惠券编码">
<a class="buyCoupon_add2 fl" href="javascript:addcode('')" id="tjcode">添加</a>
<a href="javascript:initPrice()" class="buyCoupon_add2 fl"  style="display:none" id="initcode">取消</a>
</div>
</div>
</c:if>
<div class="fr tar">
<p class="fsize12 c-333">订单总价<span class="c-master f-fG fsize16" id="oldmoney">¥0</span>  - 优惠金额 <span class="c-master f-fG fsize16" id="yhmoney"> ¥0.00</span> = <span class="c-master f-fG fsize16" id="paySumPrice">¥0</span>优惠类型:<span class="c-master" id="yhTypeId">无</span></p>
<p class="fsize24 c-333 mt20 hLh30">订单支付金额:<span class="c-master fsize36 f-fG" id="payprice">¥0</span></p>
</div>
<div class="clear"></div>
</div>
<div class="tar mt40">
<a href="javascript:order()" class="order-btn">提交订单</a>
</div>
</div>
</div>
<!--提交成功 start-->
<article class="mt30" id="order_success"   style="display: none" >
<div class="order-table pb20"  >
<section class="mt20 mr20 mb20 ml20">
<div class="orderSuccess pr ml20"  >
<ol>
<li><h2 class="hLh30 line3 pb10"><strong class="c-333 fsize20"><tt>订单号:</tt><font class="ml5 mr5 c-orange" id="orderId_success"></font>下单成功,订单总额<font class="ml5 c-orange" id="amount_success"></font></strong></h2></li>
<li><h2 class="hLh30 line3 pb10"><strong class="c-333 fsize20"><tt>帐户余额:</tt><font class="ml5 mr5 c-orange" id="balance_s" >¥0.00</font><font class="ml5 c-orange" id="bankAmount_s">,需充值¥0.00</font></strong></h2></li>
<li class="mt10">
<span class="vam"><a class="order-submit" title="" id="payNow" href="javascript:void(0)" onclick="javascript:goToBank()">立即支付</a></span>
</li>
<li class="tac"></li>
<li class="mt20"><span class="c-333 fsize14">您现在可以:<a id="repaylink" class="c-333 mr10" title="查看订单信息" href="/front/repay/"><u>返回修改支付方式</u></a> | <a class="c-4e ml10 mr10" title="进入学习中心" href="${ctx }/uc/home"><u>进入学习中心</u></a> | <a class="c-4e ml10" title="返回首页" href="${ctx }/"><u>返回首页</u></a></span></li>
</ol>
<span class="succIcon pa"></span>
</div>
</section>
</div>
</article>
<!--提交成功 end-->
</article>
</div>
</div>
我们这里建立一个shopcart.js
var payType='ALIPAY';//选择的支付方式
/** 购物车单个课程删除 */
function deleteid(id,goodsid,type) {
$.ajax({
url : baselocation + "/shopcart/ajax/deleteShopitem",
data : {
"id":id,
'goodsid' : goodsid,
"type":type
},
type : "post",
dataType : "json",
async : false,
cache : false,
success : function(result) {
queryShopCartinfo();
//重新查询购物车右侧列表
shopCartHtml();
//显示购物车数量
showshopnums();
}
});
}

//优惠券
function couponBtnClick(object){
if (!$(object).hasClass("c-on")) {
$(object).addClass("c-on");
$(object).children("tt").css({"color" : "#FF4000"});
$(".buyCouponWrap").css({"visibility" : "visible"});
} else {
$(object).removeClass("c-on");
$(object).children("tt").css({"color" : "#666"});
$(".buyCouponWrap").css({"visibility" : "hidden"});
}
}

//初始化获得购物车信息
function queryShopCartinfo() {
$.ajax({
url : baselocation + "/shopcart/ajax/queryShopCartinfo?type=1",
data : {
},
type : "post",
dataType : "text",
async : false,
cache : false,
success : function(result) {
if(result==''&&result==null){
dialog('友情提示',"购物车内没有课程,请先选购课程",1);
}else{
$("#shopingcart").html(result);
}
initPrice();
}
});
    if(!isLogin()){
lrFun();
    }
}

//显示页面课程价格,使用优惠卷时,只改变这3个div的显示即可
function initPrice(){
//显示初始化 支付金额
$("#oldmoney").html($("#div_totalMoney").html());
$("#paySumPrice").html($("#div_totalMoney").html());
$("#payprice").html($("#div_totalMoney").html());

//将优惠券的信息清除
$("#initcode").hide();
$("#tjcode").show();
$("#yhmoney").html("¥0.00");
$("#yhTypeId").html("无");
$("#couponCode").val("");
$("#couponCodeHidden").val("");

$("#queryCoupon").val('');
}
//格式化价格
function fmtprice(price){
if(typeof(price) == 'undefined' || price == null || price ==""|| isNaN(price) ||price == Infinity){
        return "¥0.00";
}else{
return "¥"+parseFloat(price).toFixed(2);
}
}

//判断订单,提交订单
function order() {
    if(!isLogin()){
lrFun();
        return ;
    }
    var buyCount=Number($("#buyCount").html());
    if(buyCount==0){
        dialog('提示信息',"购物车内没有课程,请先选购课程!",1);
        return;
    }
    var couponCode=$("#couponCodeHidden").val();//优惠券编码
    //订单提交,服务端要做验证,下单时重新查询数据库
    $.ajax({
        url: "/order?command=buy&type=1",
        data:{"payType":payType,"couponcode":couponCode},
        type:"post",
        dataType: "json",
        async : false,
        success: function(result) {
            if(result.success){
                if(isNotNull(result.entity.order)){
                    //金额页面只作为显示用,以服务端提交时重新取数据库为准
                    var orderId = result.entity.order.orderId;
                    $("#orderId").val(orderId);
                    $("#repaylink").attr("href","/front/repay/"+orderId);
                    //显示提交成功的DIV
                    $("#orderId_success").html(result.entity.order.orderNo);
                    $("#amount_success").html(fmtprice(result.entity.order.sumMoney));
                    $("#balance_s").html("¥"+result.entity.balance);
                    if(isNotEmpty(result.entity.bankAmount)){
                        $("#bankAmount_s").html(",还需充值¥"+result.entity.bankAmount);
                    }else{
                        $("#bankAmount_s").html("");
                    }
                    //$("#order_init").hide();
                    //$("#order_success").show();
                    //window.scrollTo(0,0);
//清空购物车
clearShopCart("1");
//到支付页面
setTimeout("goToBank()",1000);
//goToBank();
                }else if(result.entity.msg=='param'){
                    dialog('友情提示',"参数错误",1);
                }else if(result.entity.msg=='amount'){
                    dialog('友情提示',"购物车金额错误",1);
                }else if(result.entity.msg=='courselosedate'){
                dialog('友情提示',"购物车中有已经过期的课程,已经删除,请重新确认",17,'javascript:window.location.reload();');
                }
            }else{
dialog('下单提示',result.message,1);
            }
        },
        error : function() {
dialog('下单提示',"下单异常,请稍后再试",1);
        }
    });
}
/**
 * 选择支付宝支付
 * @param type 用于支付接口传递参数, 此处只用到0
 */
function checkbank(type){
if(type=='KUAIQIAN'){
payType='KUAIQIAN';
$("input[name='kqBank']").attr("checked",true);
$("input[name='alipay']").attr("checked",false);
$("input[name='yeepay']").attr("checked",false);
$("input[name='weixin']").attr("checked",false);
$("input[name='defaultbank']").attr("checked",false);
$("#payType").val('KUAIQIAN');
}else if(type=='ALIPAY'){
payType='ALIPAY';
$("input[name='kqBank']").attr("checked",false);
$("input[name='yeepay']").attr("checked",false);
$("input[name='weixin']").attr("checked",false);
$("input[name='defaultbank']").attr("checked",false);
$("#payType").val('ALIPAY');
}else if(type=='ALIPAY_BANK'){
payType='ALIPAY';
$("input[name='alipay']").attr("checked",false);
$("input[name='kqBank']").attr("checked",false);
$("input[name='yeepay']").attr("checked",false);
$("input[name='weixin']").attr("checked",false);
$("#payType").val('ALIPAY');
}else if(type=='YEEPAY'){
payType="YEEPAY";
$("#payType").val('YEEPAY');
$("input[name='weixin']").attr("checked",false);
$("input[name='kqBank']").attr("checked",false);
$("input[name='alipay']").attr("checked",false);
$("input[name='ALIPAY_BANK']").attr("checked",false);
}else if(type=='WEIXIN'){
payType='WEIXIN';
$("input[name='yeepay']").attr("checked",false);
$("input[name='kqBank']").attr("checked",false);
$("input[name='alipay']").attr("checked",false);
$("input[name='defaultbank']").attr("checked",false);
$("#payType").val('WEIXIN');
}
}
/**
 * 跳转到银行
 */
function goToBank(){
if(payType=='YEEPAY'){
var defaultbank=$("input[name='defaultbank']:checked").val();
if(typeof(defaultbank)!="undefined"&&defaultbank!=''){
$("#defaultbank").val(defaultbank);
}
document.orderForm.submit();
}else if(payType=='KUAIQIAN'){
document.orderForm.submit();
}else if(payType=='ALIPAY'){
var defaultbank=$("input[name='alipaybank']:checked").val();
if(typeof(defaultbank)!="undefined"&&defaultbank!=''){
$("#defaultbank").val(defaultbank);
}
document.orderForm.submit();
}else if(payType=='WEIXIN'){
document.orderForm.submit();
}else{
dialog('友情提示',"请返回选择支付方式",1);
}
}

/**
 * 下单成功后,清空购物车操作
 * @param type
 */
function clearShopCart(type){
$.ajax({
url: "/shopcart/clearShopitem/"+type,
data:{ },
type:"post",
dataType: "json",
async:true,
success: function(result) {
},
error : function() {
}
});
}
/**
 * 重新支付验证
 */
function disOrderSuccess(){
if(!isLogin()){
lrFun();
return ;
}
$.ajax({//更新订单信息
url:"/front/repayupdate",
data:{"payType":payType,"requestId":$("#orderId_success").html(),"couponcode":$("#couponCodeHidden").val()},
type:"post",
dataType:"json",
success:function(result){
if(result.message=="true"){
if(result.entity!=null){//更新订单价格
$("#balance_s").html(fmtprice(result.entity.balance));
$("#amount_success").html(fmtprice(result.entity.amount));
var bankAmount=parseFloat(result.entity.balance)-parseFloat(result.entity.amount);
if(isNotEmpty(result.entity.bankAmount)){
$("#bankAmount_s").html(",还需充值¥"+result.entity.bankAmount);
}else{
$("#bankAmount_s").html("");
}
}
goToBank();
}else if(result.message=="frozen"){
dialog('友情提示',"此优惠券已在其他订单中使用!",1);
}else{
dialog('友情提示',"订单异常,请稍后再试!",1);
}
}
})
}
//输入优惠券
function inputcode() {
if($("#couponCode").val()!=""){
$('#tjcode').show();
$("#initcode").hide();

//手动输入优惠券时  将优惠券下拉框重置
if($("#couponCode").val()!=$("#queryCoupon").val()){
$("#queryCoupon").val('');

$("#yhmoney").html("¥0.00");
$("#yhTypeId").html("无");
$("#couponCodeHidden").val("");
$("#oldmoney").html($("#div_totalMoney").html());
$("#paySumPrice").html($("#div_totalMoney").html());
$("#payprice").html($("#div_totalMoney").html());
}
}else{
$('#tjcode').hide();
$("#initcode").show();
initPrice();
}
}

//验证优惠券
function addcode(requestId){
var str=$("#couponCode").val().trim();
if(str==""||str==null){
dialog('友情提示',"请输入优惠券编号!",1);
return;
}
$.ajax({
   type: "POST",
   url: "/coupon/check",
   data: {"couponCode":str,"requestId":requestId},
   dataType : "json",
   success: function(result){
   $("#couponCodeHidden").val($("#couponCode").val());
   var obj=result.entity;
   if(result.message!='true'||obj==null){
   initPrice();
   dialog('友情提示',result.message,1);
   return false;
   }else{
   $("#tjcode").hide();
   $("#initcode").show();
   if(obj.couponCodeDTO.type==1){//折扣券
   var price=parseFloat(obj.tempPrice*obj.couponCodeDTO.amount*0.1).toFixed(2);
   var totalPrice=$("#div_totalMoney").html().replace("¥","");
   var couponPrice=subtraction(obj.tempPrice,price);
   price = totalPrice-couponPrice;
   $("#yhmoney").html('¥'+couponPrice);//优惠金额
$("#yhTypeId").html("折扣券("+parseFloat(obj.couponCodeDTO.amount).toFixed(1)+"折)");
   $("#paySumPrice").html(fmtprice(price));
   $("#payprice").html(fmtprice(price));
   }else{//定额券
   var couponPrice=parseFloat(obj.couponCodeDTO.amount).toFixed(2);
   var totalPrice=$("#div_totalMoney").html().replace("¥","");
   var price=subtraction(totalPrice,couponPrice);
   $("#yhmoney").html(fmtprice(couponPrice));//优惠金额
   $("#yhTypeId").html("立减("+fmtprice(couponPrice)+"元)");
   $("#paySumPrice").html(fmtprice(price));
   $("#payprice").html(fmtprice(price));
   }
   }
   },
   error : function (error) {
   alert(error.responseText);
   }
});
}
/**
 * 选择我的优惠券
 */
function chooseCoupon(obj){
var code=$(obj).val();
if(code==null&&code==''){
initPrice();
}else{
$("#initcode").hide();
$("#tjcode").show();
$("#yhmoney").html("¥0.00");
$("#yhTypeId").html("无");
$("#couponCode").val("");
$("#couponCodeHidden").val("");
$("#oldmoney").html($("#div_totalMoney").html());
$("#paySumPrice").html($("#div_totalMoney").html());
$("#payprice").html($("#div_totalMoney").html());
}
$("#couponCode").val(code);
$("#couponCode").click();

}

/**
   *获得支付配置
  */
public Map<String, Object> getWebsiteProfileByType(String type) {
//根据类型获得数据 从cache获取
String websiteProfileStr=(String) CacheUtil.get(CacheConstans.WEBSITE_PROFILE+type);
if(ObjectUtils.isNull(websiteProfileStr)){//cache为空查询数据库
WebsiteProfile websiteProfile=websiteProfileDao.getWebsiteProfileByType(type);
websiteProfileStr=gson.toJson(websiteProfile);//websiteProfileStr json串
CacheUtil.set(CacheConstans.WEBSITE_PROFILE+type, websiteProfileStr, CacheConstans.WEBSITE_PROFILE_TIME);//设置key 时间一天
}
WebsiteProfile websiteProfile=gson.fromJson(websiteProfileStr, WebsiteProfile.class);//转回对象
if(ObjectUtils.isNull(websiteProfile)){
websiteProfile = new WebsiteProfile();
}
String desciption=websiteProfile.getDesciption();
//把json数据转化为Map
Map<String,Object> map1=gson.fromJson(checkString(desciption), new TypeToken<Map<String, Object>>() {}.getType());
Map<String,Object> webSiteMap = new HashMap<String,Object>();
if(ObjectUtils.isNotNull(websiteProfile.getType())){
webSiteMap.put(websiteProfile.getType(), map1);
}
return webSiteMap;

}
/**
* 获取支付宝 密钥
*
* @return
*/
public Map<String, String> getAlipayInfo() {
// 获得支付配置
Map<String, Object> map = websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.alipay.toString());
JsonParser jsonParser = new JsonParser();
// 获得详细info
JsonObject jsonObject = jsonParser.parse(gson.toJson(map.get(WebSiteProfileType.alipay.toString()))).getAsJsonObject();
if (!jsonObject.isJsonNull()) {
Map<String, String> websitemap = new HashMap<String, String>();
websitemap.put("alipaykey", jsonObject.get("alipaykey").getAsString());// 支付宝key
websitemap.put("alipaypartnerID", jsonObject.get("alipaypartnerID").getAsString());// 支付宝合作伙伴id
websitemap.put("sellerEmail", jsonObject.get("sellerEmail").getAsString());// 商家
return websitemap;
}
return null;

}
public String gotoalipay(HttpServletRequest request, HttpServletResponse response, Map<String, String> sourceMap) {
try {
logger.info("+++gotoalipay sourceMap:" + sourceMap);
Map<String, String> websitemap = getAlipayInfo();// 获得支付宝配置
String requestId = sourceMap.get("requestId");// 订单支付订单号
String paygateway = "https://mapi.alipay.com/gateway.do?"; // 支付接口(不可以修改)
String service = "create_direct_pay_by_user";// 快速付款交易服务(不可以修改)
String sign_type = "MD5";// 文件加密机制(不可以修改)
//String out_trade_no = guidGeneratorService.gainCode("PAY", true);// 商户网站订单(也就是外部订单号,是通过客户网站传给支付宝,不可以重复)
String out_trade_no = "PAY"+System.currentTimeMillis();// guidGeneratorService.gainCode("PAY", true);// 商户网站订单(也就是外部订单号,是通过客户网站传给支付宝,不可以重复) 用时间戳代替了
String input_charset = OrderConstans.alipay_input_charset; // (不可以修改)
// partner和key提取方法:登陆签约支付宝账户--->点击“商家服务”就可以看到
String partner = websitemap.get("alipaypartnerID"); // 支付宝合作伙伴id
// (账户内提取)
String key = websitemap.get("alipaykey"); // 支付宝安全校验码(账户内提取)
String body = SingletonLoginUtils.getLoginUserId(request) + "-" + requestId + "-" + out_trade_no;
;// 商品描述,推荐格式:商品名称(订单编号:订单编号)
String total_fee = sourceMap.get("bankAmount");// 订单总价,差价尚须银行支付的金额
// total_fee = String.valueOf(total_fee); // 订单总价
String payment_type = "1";// 支付宝类型.1代表商品购买(目前填写1即可,不可以修改)
String seller_email = websitemap.get("sellerEmail"); // 卖家支付宝帐户
// subject 商品名称
String subject = OrderConstans.companyName + requestId;
// 扩展信息,存用户id和requestId.重要,必须存
String extra_common_param = SingletonLoginUtils.getLoginUserId(request) + "," + requestId;

String show_url = "http://" + request.getContextPath() + "/"; // 商品地址,
// 根据集成的网站而定
// 回调的地址
String path = CommonConstants.contextPath;
String notify_url = path + "/zfbpay/order/alipaynotify/1"; // 通知接收URL(本地测试时,服务器返回无法测试)
String return_url = path + "/zfbpay/order/alipaynotify/2"; // 支付完成后跳转返回的网址URL
// 注意以上两个地址 要用 http://格式的完整路径 /* 以下两个参数paymethod和defaultbank可以选择不使用,如果不使用需要注销,并在Payment类的方法中也要注销 */
String defaultbank = request.getParameter("defaultbank");
String paymethod = "directPay";
if (StringUtils.isNotEmpty(defaultbank)) {
paymethod = "bankPay";
} else {
defaultbank = null;
paymethod = "directPay";
}

String submiturl = Payment.CreateUrl(paygateway, service, sign_type, out_trade_no, input_charset, partner, key, show_url, body, total_fee, payment_type, seller_email, subject, notify_url, return_url, paymethod, defaultbank, extra_common_param);
logger.info("+++ submiturl:" + submiturl);
return "redirect:" + submiturl;
} catch (Exception e) {
logger.error(request.getContextPath(), e);
StackTraceElement[] messages = e.getStackTrace();
if (messages != null && messages.length > 0) {
StringBuffer buffer = new StringBuffer();
buffer.append(e.toString()).append("<br/>");
for (int i = 0; i < messages.length; i++) {
buffer.append(messages[i].toString()).append("<br/>");
}
request.setAttribute("myexception", buffer.toString());
}
return ERROR;
}

}
/**
 * 跳转到支付宝银行,企业支付宝, 易宝支付
 */
@RequestMapping("/order/bank")
public String gotobank(HttpServletRequest request, HttpServletResponse response, 
@RequestParam(value = "orderId", required = true) Long orderId, 
@RequestParam(value = "payType", required = true) String payType, 
@RequestParam(value = "opendId", required = true) String opendId,
@RequestParam(value = "typeOfPurchase", required = true) String typeOfPurchase,
RedirectAttributes redirectAttributes,Model model) {
try {
if(typeOfPurchase!=null&&!"".equals(typeOfPurchase.trim())&&Integer.parseInt(typeOfPurchase)>0){
request.getSession().setAttribute("typeOfPurchase", typeOfPurchase);
}else{
return "nodata";
}
// 查询订单
Order trxorder = trxorderService.queryOrderById(orderId.intValue());
if (ObjectUtils.isNotNull(trxorder)) {
// 先查询账户的金额是否足够支付本次订单的,如果购,直接走扣账流程
Map<String, String> sourceMap = new HashMap<String, String>();
sourceMap.put("total_fee", "0.00");// 充值金额,先设置为0.尝试账户余额直接支付
sourceMap.put("requestId", trxorder.getOrderNo());
sourceMap.put("userId", SingletonLoginUtils.getLoginUserId(request)+"");
sourceMap.put("payType", PayType.ACCOUNT.toString());
//不走账户支付,先写死
Map<String, String> res = new HashMap<>();
res.put(OrderConstans.RESCODE, "balance");
res.put("amount", trxorder.getSumMoney()+"");
res.put("balance", "0");
res.put("bankAmount", trxorder.getSumMoney()+"");
res.put("requestId", trxorder.getOrderNo());

// 余额支付成功,直接返回支付成功页面
if (res.get(OrderConstans.RESCODE).equals(OrderConstans.SUCCESS)) {
redirectAttributes.addAttribute(OrderConstans.RESMSG, res.get(OrderConstans.RESMSG));
//订单号
redirectAttributes.addAttribute("orderNo", trxorder.getOrderNo());
return "redirect:/front/success";
} else if ("balance".equals(res.get(OrderConstans.RESCODE))) {// 余额不足,跳转到银行页面
// 不够时,走银行流程,支付的金额为差的金额
if (payType.equals(PayType.ALIPAY.toString())) {
if("ON".equals(CacheConstans.ZHIFUBAO_IS_OPEN) && ObjectUtils.isNotNull(alipayService)){
return alipayService.gotoalipay(request, response, res);
}else{
request.setAttribute("msg","您暂未购买【支付宝支付】功能,无法使用");
return visitLimit;
}
} else if (payType.equals(PayType.YEEPAY.toString())) {
if("ON".equals(CacheConstans.YIBAO_IS_OPEN) && ObjectUtils.isNotNull(yibaoPayService)){
return yibaoPayService.gotoyp(request, response, res);
}else{
request.setAttribute("msg","您暂未购买【易宝支付】功能,无法使用");
return visitLimit;
}

} else if (payType.equals(PayType.WEIXIN.toString())) {
if("ON".equals(CacheConstans.WEIXIN_IS_OPEN) && ObjectUtils.isNotNull(weixinPayService)){
//进行微信扫码支付
String wxPayUrl = weixinPayService.getWxpayUrl(trxorder.getOrderNo(), "course");
request.setAttribute("wxPayUrl", wxPayUrl);
request.setAttribute("requestId", trxorder.getOrderNo());
request.setAttribute("orderId", trxorder.getOrderId());
request.setAttribute("type", "course");
//判断是否是微信内置浏览器,
String agent=request.getHeader("User-Agent");
if(agent.toLowerCase().indexOf("micromessenger")>-1){
request.setAttribute("weixinbrowser", "true");

//内置浏览器  并且 用户的 公众号 openid 不为空  添加jspi支付
//查询当前用户的 公众号 openid
UserProfile userProfile=new UserProfile();
userProfile.setUserid(Long.valueOf(SingletonLoginUtils.getLoginUserId(request)));
userProfile.setProfiletype(ProfileType.WEIXIN.toString());
List<UserProfile> userProfileList=userProfileService.getUserProfileList(userProfile);
if (ObjectUtils.isNotNull(userProfileList) && StringUtils.isNotEmpty(userProfileList.get(0).getValueTwo())){
//微信公众号支付请求(jspi支付)
System.out.println("微信登录,使用微信内支付");
model = weixinPayService.JSAPI(model, trxorder, userProfileList.get(0));
}else{
if(opendId==null||opendId==""){
return "redirect:"+weixinPayService.oauth2(orderId);
}else
userProfile.setValueTwo(opendId);
System.out.println("非微信登录,使用微信内支付");
model = weixinPayService.JSAPI(model, trxorder, userProfile);
}
}
//else{
//
// UserProfile userProfile=new UserProfile();
// userProfile.setUserid(Long.valueOf(SingletonLoginUtils.getLoginUserId(request)));
// userProfile.setProfiletype(ProfileType.WEIXIN.toString());
// //List<UserProfile> userProfileList=userProfileService.getUserProfileList(userProfile);
// String red_url = weixinPayService.payAPI(model, trxorder, userProfile,"MWEB");
// red_url+="&redirect_url="+URLEncoder.encode(request.getRequestURL().toString());
// //red_url+="&redirect_url="+URLEncoder.encode(CommonConstants.contextPath+"/"+qcCode);
// return "redirect:"+red_url;
//// if (ObjectUtils.isNotNull(userProfileList) && StringUtils.isNotEmpty(userProfileList.get(0).getValueTwo())){
//// System.out.println("微信登录,使用微信外 H5 支付");
//// model = weixinPayService.payAPI(model, trxorder, userProfileList.get(0),"MWEB");
//// }else{
//// if(opendId==null||opendId==""){
//// return "redirect:"+weixinPayService.oauth2(orderId);
//// }else
//// userProfile.setValueTwo(opendId);
//// System.out.println("非微信登录,微信外  H5 支付");
////
//// }
//
// }
return qcCode;
}else{
request.setAttribute("msg","您暂未购买【微信支付】功能,无法使用");
return visitLimit;
}
}
} else {// 优惠券错误信息
redirectAttributes.addAttribute(OrderConstans.RESMSG, res.get(OrderConstans.RESMSG));
//订单号
redirectAttributes.addAttribute("orderNo", trxorder.getOrderNo());
return "redirect:/front/success";
}
}
return ERROR;
} catch (Exception e) {
this.setExceptionRequest(request, e);
return ERROR;
}

}
到“支付成功”页面
<script>
var theme_color = '${theme_color}';
</script>
</head> 
<body>
<div id="aCoursesList" class="bg-fa of">
<div class="container">
<section class="path-wrap txtOf hLh30"> 
<a class="c-999 fsize14" title="" href="http://127.0.0.1">首页</a>
\<a class="c-999 fsize14" title="" href="http://127.0.0.1">购物车</a>
\<span class="c-333 fsize14">支付成功</span> 
</section>
<div class="mt30">
    <div class="order-step-bg-3 order-step"></div>
<header class="tit-zf hLh30 mt20"><span class="fsize24 c-333">支付成功</span></header>
<div class="c-pay-method c-p-m c-pay-s-box">
<div class="tac pr">
<em class="icon80 zf-cg"></em><span class="c-333 f-fH pay-font">支付成功!</span>
<div class="c-order-num"><p class="c-666 fsize16 f-fM">订单编号:<span class="c-333 fsize18">${trxorder.orderNo}</span></p></div>
</div>
<div class="mt30 pl20">
<header class="c-p-title">您的支付信息</header>
<div class="mt30 clearfix of">
<div class="fl zf-list">
<ul class="order-list-item ml20">
<li class="o-l-fir"><em class="icon-14 c-o-icon"></em><span class="fsize14 c-999 f-fM ml5 vam">付款金额:<tt class="c-master f-fG fsize30">¥${trxorder.sumMoney}</tt></span></li>
<li><em class="icon-14 c-o-icon mt5"></em><span class="fsize14 c-999 f-fM  ml5 vam">支付方式:
<tt class="c-333 f-fM">
<c:choose>
<c:when test="${trxorder.payType=='ALIPAY'}">支付宝</c:when>
<c:when test="${trxorder.payType=='WEIXIN'}">微信</c:when>
<c:when test="${trxorder.payType=='YEEPAY'}">易宝</c:when>
<c:when test="${trxorder.payType=='CARD'}">课程卡</c:when>
<c:when test="${trxorder.payType=='ACCOUNT'}">账户余额</c:when>
<c:when test="${trxorder.payType=='USERCARD'}">学员卡</c:when>
</c:choose>
</tt></span></li>
<li><em class="icon-14 c-o-icon"></em><span class="fsize14 c-999 f-fM  ml5 vam">支付日期:<tt class="c-333 f-fM"><fmt:formatDate value="${trxorder.payTime}" pattern="yyyy-MM-dd HH:mm"></fmt:formatDate> </tt></span></li>
<li><em class="icon-14 c-o-icon"></em><span class="fsize14 c-999 f-fM  ml5 vam c-buy-cou">所购课程:<tt class="c-333 f-fM">
<c:forEach items="${courseList}" var="course">
《${course.courseName}》
</c:forEach>
</tt></span></li>
</ul>
</div>
<div class="fr mr30 pay-nav-return clearfix">
<div class="mt10 w50"><a href="${ctx}" class="blue-btn blue-1-btn"><em class="icon20"></em><tt>返回首页</tt></a></div>
<c:if test="${typeOfPurchase eq 1}">
      <div class="mt30 w50"><a href="javascript:tostudy()" class="blue-btn blue-1-btn lea-cou-btn"><em class="icon20"></em><tt>学习课程</tt></a></div>
</c:if>
<script>
//如果是直播则调到我的直播 如果是课程则调到我的课程
function tostudy(){
var coursetype ='${courseList[0].sellType}';
if(coursetype=='LIVE'){
window.location.href="/uc/live";
}else{
window.location.href="/uc/index";
}
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
if("${msg}"!=null && "${msg}"!=''){
dialog('提示信息',decodeURI("${msg}"),0);
}
})
</script>
</body>
ok,大功告成,到目前为止我们的购物车功能和支付功能已全部完成!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: