<?php

// 用户购买视频支付接口
require_once ("../user_include.inc");

ErrorLogger::doOutput("Compass...ajax_set_buy_media.php.php....Start.", 0);

//获取参数
$unionId = ParamUtil::getRequestString("unionId");
$openId = ParamUtil::getRequestString("openId", 0);
$courseId = ParamUtil::getRequestNumber("courseId", 0);
$mediaId = ParamUtil::getRequestNumber("mediaId", 0);

$result = array();

//参数检查
if(empty($unionId) || empty($openId)|| empty($courseId)|| empty($mediaId)) {
	$result["message"] = "参数错误！";
	responseNG($result);
}

$result = array();

//判断用户是否存在
$param = array();
$param['unionid'] = $unionId;
$param['openid'] = $openId;
$param['delete_flg'] = false;
$userList = UserMst::getList($param,'id','desc', 0, 1);
if(empty($userList)) {
	$result["message"] = "用户不存在！";
	responseNG($result);
}
$userMst = $userList[0];

//判断视频是否存在
$param = array();
$param['id'] = $mediaId;
$param['course_id'] = $courseId;
$param['delete_flg'] = false;
$courseMediaList = CourseMediaDat::getList($param,'id','desc', 0, 1);
if(empty($courseMediaList)) {
	$result["message"] = "视频不存在！";
	responseNG($result);
}
$courseMediaDat = $courseMediaList[0];

//用户是否已经购买本视频
$param = array();
$param['user_id'] = $userMst->id;
$param['course_id'] = $courseId;
$param['media_id'] = $courseMediaDat->id;
$param['is_free'] = false;
$param['status'] = 'SUCCESS';
$param['delete_flg'] = false;
$userBuyMediaList = UserMediaDat::getList($param, "id", "desc", 0, 1);
if(!empty($userBuyMediaList)) {
	$result["message"] = "不能重复购买！";
	responseNG($result);
}

//调用微信支付

//生成临时订单
$orderNo = "M" . date("YmdHis") . "_" . $userMst->id;
$userMediaDat = new UserMediaDat();
$userMediaDat->user_id = $userMst->id;
$userMediaDat->course_id = $courseId;
$userMediaDat->media_id = $mediaId
$userMediaDat->is_free = false;
$userMediaDat->money = $courseMediaDat->price;
$userMediaDat->order_no = $orderNo;
$userMediaDat->status = "NEW";
$userMediaDat->save();

//调用微信支付接口
$tools = new JsApiPay();
$input = new WxPayUnifiedOrder();
$input->SetBody($courseMediaDat->title);
$input->SetAttach($courseMediaDat->title);
$input->SetOut_trade_no($orderNo);
$input->SetTotal_fee($courseMediaDat->price * 100);//折算到分
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 800));
$input->SetGoods_tag($courseMediaDat->title);
$input->SetNotify_url("https://" . SSL_PATH . "/api/api_wx_pay_notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($userMst->openid);

$order = WxPayApi::unifiedOrder($input);

$jsApiParameters = $tools->GetJsApiParameters($order);
ErrorLogger::doOutput($jsApiParameters);
ErrorLogger::doOutput("Compass...ajax_set_buy_media.php.php....End.", 0);
//已经被 encode一次了，先还原为数组。
responseOK(json_decode($jsApiParameters));

?>