<?php

// 更新用户会员状态
require_once ("../user_include.inc");

$unionId = ParamUtil::getRequestString("unionId", 0);
$openId = ParamUtil::getRequestString("openId", 0);
$mediaId = ParamUtil::getRequestString("mediaId", 0);
ErrorLogger::doOutput("Compass...ajax_buy_course_media.php....Start.", 0);

ErrorLogger::doOutput("Compass...ajax_buy_course_media.php....unionId=" . $unionId, 0);

//参数验证
if(empty($unionId) || empty($openId)) {
	responseNG("参数错误！");
}

//检索用户是否存在
$param['unionid'] = $unionId;
$param['openId'] = $openId;
$param['delete_flg'] = false;
$tmpUserMstList = UserMst::getList($param,'id','desc', 0, 1);
if(empty($tmpUserMstList)) {
	responseNG("参数错误！");
}

$userMst = $tmpUserMstList[0];

//媒体是否存在
$courseMediaDat = CourseMediaDat::getById($mediaId);
if(empty($courseMediaDat)) {
	$result["message"] = "视频不存在！";
	responseNG($result);
}

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

ErrorLogger::doOutput("Compass...ajax_buy_course_media.php....SetNotify_url=" . "https://" . SSL_PATH . "/api/api_wx_pay_notify.php", 0);

//调用微信支付接口
$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_buy_course_media.php....End.", 0);

responseOK($jsApiParameters);

function responseNG($message) {
	$result = array("status"=>"NG", "message"=>$message);
	print json_encode($result);
	exit;
}
function responseOK($result) {
	$result = array("status"=>"OK", "result"=>$result);
	print json_encode($result);
	exit;
}
?>