<?php
require '../conn/conn.php';
require '../conn/function.php';

$action=$_GET["action"];
$id=intval($_GET["id"]);
if($id==0){
    $id=getrs("select * from sl_product where P_mid=0 order by P_order asc,P_id desc","P_id");
    $_GET["show"]="none";
}
sql("update sl_product set P_view=P_view+1 where P_id=".$id);
$P=getrs("select * from sl_product where P_id=$id and P_sh=1 and P_del=0");
if($P==""){
    die(error("商品未发布或未审核，请重新检查！"));
}

if($P["P_mid"]>0){//入驻商家
    $M=getrs("select * from sl_member where M_id=".$P["P_mid"]);
    $mid=$M["M_id"];
    $maincontact=$M["M_maincontact"];
    $qq=$M["M_qq"];
    $mobile=$M["M_mobile"];
    $wechat=$M["M_wechat"];
    $wechatcode=$M["M_wechatcode"];
    $webtitle=$M["M_webtitle"];
    $keyword=$M["M_keyword"];
    $description=$M["M_description"];
    $ico=$M["M_ico"];
    $logo=$M["M_logo"];
    $notice=$M["M_notice"];
    $shopt=$M["M_shopt"];
    if($M["M_money"]<0){
        die(error("商户余额不足，无法发起交易，请先充值！"));
    }
    if($M["M_stop"]==1){
        die(error("该商户已被封停，原因：".$M["M_reason"]."！"));
    }

    if($C_pay==0){//商户自行收款
        $pid=$M["M_pid"];
        $pkey=$M["M_pkey"];
        $payurl=$M["M_payurl"];
        $alipayon=$M["M_alipayon"];
        $wxpayon=$M["M_wxpayon"];

    }else{//平台代收款
        $pid=$C["C_pid"];
        $pkey=$C["C_pkey"];
        $payurl=$C["C_payurl"];
        $alipayon=$C["C_alipayon"];
        $wxpayon=$C["C_wxpayon"];

    }
    if(($maincontact==0 && $qq=="") || ($maincontact==1 && $mobile=="") || ($maincontact==2 && $wechat=="")){
        die(error("请先完善客服联系方式！（卖家中心→店铺设置→基本设置→联系方式）"));
    }
}else{//自营店
    $C=getrs("select * from sl_config");
    $pid=$C["C_pid"];
    $pkey=$C["C_pkey"];
    $payurl=$C["C_payurl"];
    $mid=0;
    $maincontact=$C["C_maincontact"];
    $qq=$C["C_qq"];
    $mobile=$C["C_mobile"];
    $wechat=$C["C_wechat"];
    $wechatcode=$C["C_wechatcode"];
    $webtitle=$C["C_webtitle"];
    $keyword=$C["C_keyword"];
    $description=$C["C_description"];
    $ico=$C["C_ico"];
    $logo=$C["C_logo"];
    $notice=$C["C_notice"];
    $alipayon=$C["C_alipayon"];
    $wxpayon=$C["C_wxpayon"];
    $shopt=$C["C_shopt"];

    if(($maincontact==0 && $qq=="") || ($maincontact==1 && $mobile=="") || ($maincontact==2 && $wechat=="")){
        die(error("请先完善客服联系方式！（后台→网站设置→基本设置→联系方式）"));
    }
}

if($action=="pay"){
    $no=t($_REQUEST["no"]);
    $amount=intval($_REQUEST["amount"]);
    $address=t($_REQUEST["address"]);
    $pay_type=t($_REQUEST["pay_type"]);
    $money=$amount*$P["P_price"];
    
    if($P["P_from"]==0){
        if($P["P_selltype"]==0){
            $rest=9999999;
            if($amount>1){
                die("{\"code\":\"error\",\"msg\":\"本商品只可购买一件\"}");
            }
        }else{
            $rest=get_json_num($P["P_card"],"sell","0");
        }
    }else{
        $DP=getrs("select * from sl_product where P_id=".$P["P_from"]);
        if($DP["P_selltype"]==0){
            $rest=9999999;
            if($amount>1){
                die("{\"code\":\"error\",\"msg\":\"本商品只可购买一件\"}");
            }
        }else{
            $rest=get_json_num($DP["P_card"],"sell","0");
        }
    }

    if($P["P_from"]>0 && $C_pay==0){
        die("{\"code\":\"error\",\"msg\":\"平台收款模式为“商家自行收款”，不支持购买对接商品\"}");
    }
    
    if($money>0){
        if($address!=""){
            if($rest-$amount>=0){

                if(getrs("select O_id from sl_orders where O_no='$no'","O_id")==""){
                    sql("insert into sl_orders(O_title,O_price,O_num,O_address,O_mid,O_no,O_time,O_paytype,O_pid,O_content) values('".$P["P_title"]."',".$P["P_price"].",$amount,'$address',".$mid.",'$no','".date('Y-m-d H:i:s')."','$pay_type',".$P["P_id"].",'')");
                }else{
                    sql("update sl_orders set O_num=$amount,O_address='$address',O_time='".date('Y-m-d H:i:s')."',O_paytype='$pay_type' where O_no='$no'");
                }

                if($pay_type=="e_alipay" || $pay_type=="e_wxpay"){
                    $title=mb_substr($P["P_title"],0,10,"utf-8")."...-购买";
                    $notify_url=gethttp().$domain."/shop/notify.php";
                    $return_url=gethttp().$domain."/shop/epay_return.php";
                    $arr = array(
                    	"pid" => $pid,
                    	"type" => splitx($pay_type,"_",1),
                    	"notify_url" => $notify_url,
                        "return_url" => $return_url,
                    	"out_trade_no" => $no,
                    	"name" => $title,
                    	"money"	=> $money,
                    	"sign_type"	=> "MD5"
                    );
                    
                    $sign=get_sign($arr,$pkey);
                    
                    die("{\"code\":\"success\",\"paytype\":\"".$pay_type."\",\"url\":\"".$payurl."/submit.php?name=$title&money=$money&out_trade_no=$no&notify_url=$notify_url&pid=$pid&return_url=$return_url&sign=$sign&sign_type=MD5&type=".splitx($pay_type,"_",1)."\"}");
                }
                if($pay_type=="alipay"){
                    $title=mb_substr($P["P_title"],0,10,"utf-8")."...-购买";
                    $notify_url=gethttp().$domain."/shop/alipay_notify.php";
                    $return_url=gethttp().$domain."/shop/alipay_return.php";

                    $requestConfigs = array(
                        'product_code'=>'FAST_INSTANT_TRADE_PAY',  //订单标题
                        'out_trade_no'=>$no,
                        'total_amount'=>$money, //单位 元
                        'subject'=>$title,  //订单标题
                        'body'=>$title,  //订单标题
                    );
                    if(isMobile()){
                        $commonConfigs = array(
                            'app_id' => $C_alipay_appid,
                            'method' => 'alipay.trade.wap.pay',             //接口名称
                            'format' => 'JSON',
                            'charset'=>'utf-8',
                            'sign_type'=>'RSA2',
                            'timestamp'=>date('Y-m-d H:i:s'),
                            'version'=>'1.0',
                            'notify_url' => $notify_url,
                            'return_url' => $return_url,
                            'biz_content'=>json_encode($requestConfigs),
                        );
                    }else{
                        $commonConfigs = array(
                            //公共参数
                            'app_id' => $C_alipay_appid,
                            'method' => 'alipay.trade.page.pay',             //接口名称
                            'format' => 'JSON',
                            'charset'=>'utf-8',
                            'sign_type'=>'RSA2',
                            'timestamp'=>date('Y-m-d H:i:s'),
                            'version'=>'1.0',
                            'notify_url' => $notify_url,
                            'return_url' => $return_url,
                            'biz_content'=>json_encode($requestConfigs),
                        );
                    }
                    
                    $commonConfigs["sign"] = generateSign($commonConfigs,'RSA2');
                    die("{\"code\":\"success\",\"url\":\"https://openapi.alipay.com/gateway.do?".http_build_query($commonConfigs)."\"}");
                }
                if($pay_type=="wxpay"){
                    die("{\"code\":\"success\",\"url\":\"".gethttp().$domain."/shop/wxpay.php?no=$no\"}");
                }
            }else{
                die("{\"code\":\"error\",\"msg\":\"库存仅剩".$rest."件，请修改购买数量\"}");
            }
        }else{
            die("{\"code\":\"error\",\"msg\":\"请填写联系方式\"}");
        }
    }else{
        die("{\"code\":\"error\",\"msg\":\"订单金额有误\"}");
    }
}

if($P["P_from"]==0){//自建商品
    if($P["P_selltype"]==0){
        $rest_title="库存充足";
        $rest=999999;
    }else{
        $rest_title="剩余".get_json_num($P["P_card"],"sell","0")."件";
        $rest=get_json_num($P["P_card"],"sell","0");
    }
}else{//对接商品
    $DP=getrs("select * from sl_product where P_id=".$P["P_from"]);
    if($DP["P_selltype"]==0){
        $rest_title="库存充足";
        $rest=999999;
    }else{
        $rest_title="剩余".get_json_num($DP["P_card"],"sell","0")."件";
        $rest=get_json_num($DP["P_card"],"sell","0");
    }
}

require 'template/'.$shopt.'/index.php';

function generateSign($data, $signType){
    global $C_alipay_key2;
    ksort($data);
    $stringToBeSigned = "";
    $i = 0;
    foreach ($data as $k => $v) {
        if ($v!="" && "@" != substr($v, 0, 1)) {
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
    }
    unset ($k, $v);
    $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
        wordwrap($C_alipay_key2, 64, "\n", true) .
        "\n-----END RSA PRIVATE KEY-----";
    ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
    if ("RSA2" == $signType) {
        openssl_sign($stringToBeSigned, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
    } else {
        openssl_sign($stringToBeSigned, $sign, $res);
    }
    $sign = base64_encode($sign);
    return $sign;
}
?>