<?php
$lid =1;
$sid =1;
define('IN_WEB', true);
include (dirname(__FILE__)."/../com.php");
$ts = date("Y-m-d H:i:s",time());
$uniqId = uniqid();
$googleData = file_get_contents('php://input');
if(!empty($googleData)){
    $googleData = json_decode($googleData,true);
    oo::logs()->commlog(["time"=>$ts,"info"=>$googleData,"type"=>"join","uniqId"=>$uniqId,"sid"=>1],'and-vip.log','logs/'.date('Ymd').'/');
    $purchaseData  = base64_decode($googleData['message']['data']);
    oo::logs()->commlog(["time"=>$ts,"info"=>$purchaseData,"type"=>"join","uniqId"=>$uniqId,"sid"=>2],'and_vip_decode.log');
//    if(empty($purchaseData)){
//        oo::logs()->debug5($googleData,'vip.log','logs/'.date('Ymd').'/');
//    }
    $purchaseData = json_decode($purchaseData,true);
    $packageName   = $purchaseData['packageName'];
    $productId     = $purchaseData['subscriptionNotification']['subscriptionId'];
    $purchaseToken = $purchaseData['subscriptionNotification']['purchaseToken'];
    $notificationType = $purchaseData['subscriptionNotification']['notificationType'];
    //if($notificationType == 13 || $notificationType == 3 || $notificationType == 12){
  	if($notificationType == 13){
        $tb  = otable::subscription();
        $sql = "SELECT * FROM {$tb} WHERE purchaseToken='{$purchaseToken}'";
        $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
        if($ret){
            $updateInfo['svip'] = 0;
            oo::commonOprModel('member')->getUserInfo($ret['uid'], NULL, TRUE,$updateInfo);
        }
    }else if($notificationType == 4){
        $tb  = otable::subscription();
        $sql = "SELECT * FROM {$tb} WHERE purchaseToken='{$purchaseToken}'";
        $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
//        if(empty($ret)){
//            oo::logs()->debug5(['time'=>time(),'purchaseToken'=> $purchaseToken],'vip.log','logs/'.date('Ymd').'/');
//        }
    }else if($notificationType == 2 || $notificationType == 1){
        oo::commonOprRedis('common')->delete($purchaseToken); // 删除缓存
        $purchaseInfo  = oo::commonOprModel('Paymentgoogle')->getUserSubscribeStatus($packageName,$productId,$purchaseToken);
        if(!empty($purchaseInfo)){
            $expiryTimeMillis = ceil($purchaseInfo['expiryTimeMillis']/1000);
            $tb  = otable::subscription();
            $sql = "SELECT * FROM {$tb} WHERE purchaseToken='{$purchaseToken}'";
            $ret = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
            if($ret){
                $uid = $ret['uid'];
                $curUserInfo = oo::commonOprModel('member')->getUserInfo($uid);
                if($curUserInfo['vip_expire'] < $expiryTimeMillis){
                    $updateInfo['svip'] = 1;
                    $updateInfo['svip_expire'] = $expiryTimeMillis;
                    oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE,$updateInfo);
                    $tb  = otable::goodsCrazy();
                    $sku = oo::commonOprModel('goods')->googleSkuToAndroid($productId);
                    $sql = "SELECT * FROM {$tb} WHERE gsku='{$sku}' LIMIT 1";
                    $serialNo = $purchaseInfo['orderId'];
                    $goodInfo = oo::commonOprDb('payment')->getOne($sql,MYSQLI_ASSOC);
                    $tpStatus = intval(oo::commonOprRedis('common')->hGet(okeys::vipTurnTable(),$uid));
                    $setSpins = oo::commonOprModel('readconfig')->getCon('basic','restoreSpins');
                    $setSpins += intval(oo::commonOprModel('readconfig')->getCon('vip','refreshSpins'));
                    $arr = [
                        'uid'      => $uid,
                        'gid'      => empty($goodInfo['gid']) ? 801 : $goodInfo['gid'],
                        'ggameid'  => $goodInfo['ggameid'],
                        'flag'     => 1,
                        'serialNo' => $serialNo,
                    ];
                    $data = oo::commonOprModel('payment')->createOrder($arr);
                    $orderId = $data['orderId'];
                    $time = time();
                    $paymenttb = otable::payment($uid);
                    $sql = " UPDATE {$paymenttb} SET status = 2,pay_time={$time},use_time={$time},platform_serial_num = '{$serialNo}' WHERE uid = {$uid} AND order_id = {$orderId} AND status = 1 LIMIT 1";
                    oo::commonOprDb('payment')->query($sql);
                    $table = otable::summarylist();
                    $sqlUpdateSummary = " UPDATE {$table} SET sl_platform_serial_num='{$serialNo}',sl_status = 2, sl_pay_time = {$time} WHERE sl_uid = {$uid} AND sl_orderid = '{$orderId}' LIMIT 1";
                    oo::commonOprDb('payment')->query($sqlUpdateSummary);
                    /**
                     * vip 续订记录
                     */
                    oo::commonOprRedis('User')->incr(okeys::VipRenewTimes($uid)) && oo::commonOprRedis('User')->expire(okeys::VipRenewTimes($uid),15*24*60*60);
                    oo::commonOprModel('Workerman')->push($uid,ocmd::$send['Vip_Rec'],['vipInfo'=>oo::commonOprModel('newvip')->getVipInfo($uid)]);
                    oo::async()->add('oo::commonOprModel("notice")->sendNoticeMsg',[$uid,"buyVip"]);//异步跑马灯消息
                }
            }else{
                oo::logs()->commlog(["time"=>$ts,"info"=>"","type"=>"statusError","uniqId"=>$uniqId,"sid"=>1],'vipNew.log','logs/'.date('Ymd').'/');
//                oo::logs()->debug5($purchaseInfo,'vip_err.log');
            }
        }
    }
}
die(oo::response(1));
?>

<!-- notificationType -->
<!--(1)  SUBSCRIPTION_RECOVERED - 从帐号保留状态恢复了订阅。-->
<!--(2)  SUBSCRIPTION_RENEWED   - 续订了处于活动状态的订阅。-->
<!--(3)  SUBSCRIPTION_CANCELED  - 自愿或非自愿地取消了订阅。如果是自愿取消，在用户取消时发送。-->
<!--(4)  SUBSCRIPTION_PURCHASED - 购买了新的订阅。-->
<!--(5)  SUBSCRIPTION_ON_HOLD   - 订阅已进入帐号保留状态（如已启用）。-->
<!--(6)  SUBSCRIPTION_IN_GRACE_PERIOD - 订阅已进入宽限期（如已启用）。-->
<!--(7)  SUBSCRIPTION_RESTARTED - 用户已通过“Play”>“帐号”>“订阅”重新激活其订阅（需要选择使用订阅恢复功能）。-->
<!--(8)  SUBSCRIPTION_PRICE_CHANGE_CONFIRMED - 用户已成功确认订阅价格变动。-->
<!--(9)  SUBSCRIPTION_DEFERRED  - 订阅的续订时间点已延期。-->
<!--(12) SUBSCRIPTION_REVOKED   - 用户在有效时间结束前已撤消订阅。-->
<!--(13) SUBSCRIPTION_EXPIRED   - 订阅已过期。-->

<!--/**-->
<!--* notificationType    int-->
<!--* 通知的类型。它可以具有以下值：-->
<!--* (1) SUBSCRIPTION_RECOVERED - 从帐号保留状态恢复了订阅。-->
<!--* (2) SUBSCRIPTION_RENEWED - 续订了处于活动状态的订阅。-->
<!--* (3) SUBSCRIPTION_CANCELED - 自愿或非自愿地取消了订阅。如果是自愿取消，在用户取消时发送。-->
<!--* (4) SUBSCRIPTION_PURCHASED - 购买了新的订阅。-->
<!--* (5) SUBSCRIPTION_ON_HOLD - 订阅已进入帐号保留状态（如已启用）。-->
<!--* (6) SUBSCRIPTION_IN_GRACE_PERIOD - 订阅已进入宽限期（如已启用）。-->
<!--* (7) SUBSCRIPTION_RESTARTED - 用户已通过“Play”>“帐号”>“订阅”重新激活其订阅（需要选择使用订阅恢复功能）。-->
<!--* (8) SUBSCRIPTION_PRICE_CHANGE_CONFIRMED - 用户已成功确认订阅价格变动。-->
<!--* (9) SUBSCRIPTION_DEFERRED - 订阅的续订时间点已延期。-->
<!--* (10) SUBSCRIPTION_PAUSED - 订阅已暂停。-->
<!--* (11) SUBSCRIPTION_PAUSE_SCHEDULE_CHANGED - 订阅暂停计划已更改。-->
<!--* (12) SUBSCRIPTION_REVOKED - 用户在有效时间结束前已撤消订阅。-->
<!--* (13) SUBSCRIPTION_EXPIRED - 订阅已过期。-->
<!--*/-->

