shish 6 年 前
コミット
13d9480132

+ 21 - 27
biz/stat/services/StatIncomeSourceMonthService.php

@@ -4,34 +4,28 @@ namespace biz\stat\services;
 
 use biz\base\services\BaseService;
 use common\components\business;
-use common\components\validate;
-use Yii;
 
 class StatIncomeSourceMonthService extends BaseService
 {
-	
-	public static $baseFile = '\biz\stat\classes\StatIncomeSourceMonthClass';
-	
-	
-	//添加更新记录 shish 2019.9.16
-	public static function replaceData($data)
-	{
-		$valid = ['sourceType', 'amount', 'merchantId', 'payWay'];
-		validate::easyCheck($valid, $data);
-		$merchantId = $data['merchantId'];
-		$sourceType = $data['sourceType'];
-		$amount = $data['amount'];
-		$data['year'] = isset($data['year']) ? $data['year'] : date("Y");
-		$data['month'] = isset($data['month']) ? $data['month'] : date("n");
-		$income = self::getByCondition(['merchantId' => $merchantId, 'year' => $data['year'], 'month' => $data['month'], 'sourceType' => $sourceType], true);
-		if (empty($income)) {
-			$income = self::add($data, true);
-		} else {
-			$income->amount += $amount;
-		}
-		$income = business::savePayWayAmount($income, $amount, $data['payWay']);
-		$income->save();
-		return true;
-	}
-	
+
+    public static $baseFile = '\biz\stat\classes\StatIncomeSourceMonthClass';
+
+    //添加更新记录 shish 2019.9.16
+    public static function replaceData($data)
+    {
+        $merchantId = $data['merchantId'];
+        $sourceType = $data['sourceType'];
+        $amount = $data['amount'];
+        $data['time'] = isset($data['time']) ? $data['time'] : date("Ym");
+        $income = self::getByCondition(['merchantId' => $merchantId, 'time' => $data['time'], 'sourceType' => $sourceType], true);
+        if (empty($income)) {
+            $income = self::add($data, true);
+        } else {
+            $income->amount += $amount;
+        }
+        $income = business::savePayWayAmount($income, $amount, $data['payWay']);
+        $income->save();
+        return true;
+    }
+
 }

+ 55 - 57
biz/stat/services/StatIncomeSourceService.php

@@ -12,61 +12,59 @@ use Yii;
 
 class StatIncomeSourceService extends BaseService
 {
-	
-	public static $baseFile = '\biz\stat\classes\StatIncomeSourceClass';
-	
-	//添加更新记录 shish 2010.8.20
-	public static function replaceData($data)
-	{
-		$valid = ['merchantId', 'sourceType', 'amount', 'payWay'];
-		validate::easyCheck($valid, $data);
-		$time = isset($data['time']) ? $data['time'] : date("Ymd");
-		if (strtotime($time) == false) {
-			util::fail('不是日期格式');
-		}
-		$payWay = $data['payWay'];
-		$merchantId = $data['merchantId'];
-		$sourceType = $data['sourceType'];
-		$amount = $data['amount'];
-		$addTime = time();
-		$income = self::getByCondition(['merchantId' => $merchantId, 'time' => $time, 'sourceType' => $sourceType], true);
-		if (empty($income)) {
-			$data['time'] = $time;
-			$data['addTime'] = $addTime;
-			$income = self::add($data, true);
-		} else {
-			$income->amount += $amount;
-		}
-		$income = business::savePayWayAmount($income, $amount, $payWay);
-		$income->save();
-		
-		/**每个月增加**/
-		StatIncomeSourceMonthService::replaceData($data);
-		
-		return true;
-	}
-	
-	//取最近的按来源分的收入 shish 2019.9.21
-	public static function getLatestSource($start, $end, $merchantId)
-	{
-		$list = self::getAllList('sourceType,amount', ['merchantId' => $merchantId, 'time' => ['between', [$start, $end]]], 'time asc');
-		$data = [];
-		$sourceType = UserClass::$sourceType;
-		$totalAmount = 0;
-		if (!empty($list)) {
-			foreach ($sourceType as $id => $item) {
-				$data[$id]['name'] = $item;
-				$data[$id]['value'] = 0;
-			}
-			foreach ($list as $key => $val) {
-				$currentSourceType = $val['sourceType'];
-				$amount = $val['amount'];
-				$data[$currentSourceType]['value'] = stringUtil::calcAdd($data[$currentSourceType]['value'], $amount);
-				$totalAmount = stringUtil::calcAdd($totalAmount, $amount);
-			}
-		}
-		
-		return ['data' => array_values($data), 'sourceTypeName' => $sourceType, 'totalAmount' => $totalAmount];
-	}
-	
+
+    public static $baseFile = '\biz\stat\classes\StatIncomeSourceClass';
+
+    //添加更新记录 shish 2010.8.20
+    public static function replaceData($data)
+    {
+        $time = isset($data['time']) ? $data['time'] : date("Ymd");
+        if (strtotime($time) == false) {
+            util::fail('不是日期格式');
+        }
+        $payWay = $data['payWay'];
+        $merchantId = $data['merchantId'];
+        $sourceType = $data['sourceType'];
+        $amount = $data['amount'];
+        $addTime = time();
+        $income = self::getByCondition(['merchantId' => $merchantId, 'time' => $time, 'sourceType' => $sourceType], true);
+        if (empty($income)) {
+            $data['time'] = $time;
+            $data['addTime'] = $addTime;
+            $income = self::add($data, true);
+        } else {
+            $income->amount += $amount;
+        }
+        $income = business::savePayWayAmount($income, $amount, $payWay);
+        $income->save();
+
+        /**每个月增加**/
+        StatIncomeSourceMonthService::replaceData($data);
+
+        return true;
+    }
+
+    //取最近的按来源分的收入 shish 2019.9.21
+    public static function getLatestSource($start, $end, $merchantId)
+    {
+        $list = self::getAllList('sourceType,amount', ['merchantId' => $merchantId, 'time' => ['between', [$start, $end]]], 'time asc');
+        $data = [];
+        $sourceType = UserClass::$sourceType;
+        $totalAmount = 0;
+        if (!empty($list)) {
+            foreach ($sourceType as $id => $item) {
+                $data[$id]['name'] = $item;
+                $data[$id]['value'] = 0;
+            }
+            foreach ($list as $key => $val) {
+                $currentSourceType = $val['sourceType'];
+                $amount = $val['amount'];
+                $data[$currentSourceType]['value'] = stringUtil::calcAdd($data[$currentSourceType]['value'], $amount);
+                $totalAmount = stringUtil::calcAdd($totalAmount, $amount);
+            }
+        }
+
+        return ['data' => array_values($data), 'sourceTypeName' => $sourceType, 'totalAmount' => $totalAmount];
+    }
+
 }

+ 281 - 283
common/services/xhMerchantAssetService.php

@@ -19,289 +19,287 @@ use common\services\xhOrderGoodsService;
 
 class xhMerchantAssetService
 {
-	
-	public static function getByMerchantId($id)
-	{
-		$condition = ['merchantId' => $id];
-		$merchant = xhMerchantAsset::getByCondition($condition);
-		return $merchant;
-	}
-	
-	/**
-	 * 资产初始化,计算总量保存到xhMerchantAsset
-	 */
-	public static function assetInit($merchantId)
-	{
-		set_time_limit(0);
-		//计算总收入
-		$income = Yii::$app->db->createCommand("SELECT SUM(amount) as totalIncome FROM xhMerchantCapital WHERE io=1 and merchantId={$merchantId}")->queryOne();
-		$totalIncome = $income['totalIncome'];
-		//计算总粉丝数
-		$totalFans = xhUser::find()->andWhere(['subscribe' => 1, 'merchantId' => $merchantId])->count('id');
-		//计算访问总量
-		$visit = Yii::$app->db->createCommand("SELECT SUM(riseNum) as num FROM xhStatVisitByDay WHERE merchantId={$merchantId}")->queryOne();
-		$totalVisit = $visit['num'];
-		//计算总交易量
-		$totalDeal = xhMerchantCapital::find()->andWhere(['io' => 1, 'merchantId' => $merchantId])->count('id');
-		$data = ['totalDeal' => $totalDeal, 'totalVisit' => $totalVisit, 'totalFans' => $totalFans, 'totalIncome' => $totalIncome];
-		self::updateByMerchantId($merchantId, $data);
-	}
-	
-	public static function updateByMerchantId($merchantId, $data)
-	{
-		xhMerchantAsset::updateByCondition(['merchantId' => $merchantId], $data);
-		return self::refreshByMerchantId($merchantId);
-	}
-	
-	public static function refreshByMerchantId($merchantId)
-	{
-		$key = configDict::getCacheKey('merchantAsset') . $merchantId;
-		Yii::$app->redis->executeCommand('DEL', [$key]);
-		return self::getByMerchantId($merchantId);
-	}
-	
-	//收入后资产变更 shish 2019.12.24
-	public static function incomeChangeAsset($merchant, $merchantAsset, $updateData, $order, $capitalType)
-	{
-		$merchantId = $merchant['id'];
-		$openMerchant = xhWxOpenService::getMerchant();
-		$openMerchantId = $openMerchant['id'];
-		$orderId = $order['id'];
-		$date = date("Y-m-d H:i");
-		$totalFee = 0;
-		$payWayList = configDict::getConfig('payWayName');
-		$payWay = isset($order['payWay']) ? $order['payWay'] : 0;
-		$payWay = $payWayList[$payWay];
-		$userId = isset($order['userId']) ? $order['userId'] : 0;
-		$user = xhUserService::getById($userId);
-		$userName = isset($user['userName']) ? $user['userName'] : '游客';
-		//充值支付涉及的流水类型列表
-		$typeList = configDict::getConfig('capitalType');
-		//根据流水类型定制通知内容
-		switch ($capitalType) {
-			//购买商品
-			case $typeList['xhOrder']['id']:
-				$orderName = $order['bookName'];
-				$totalFee = $order['actPrice'];
-				$goodsList = xhOrderGoodsService::getAllByOrderId($orderId);
-				if (!empty($goodsList)) {
-					foreach ($goodsList as $goodsKey => $goodsVal) {
-						$goodsId = $goodsVal['goodsId'];
-						$goods = xhGoodsService::getById($goodsId);
-						if (!empty($goods)) {
-							$actualSold = stringUtil::calcAdd($goods['actualSold'], 1);
-							xhGoodsService::updateById($goodsId, ['actualSold' => $actualSold]);//商品被售出数量+1
-						}
-					}
-				}
-				if ($order['sourceType'] == 0) {
-					//商城下单后通知
-					//$data = [];
-					//InformAdminService::goodsSoldInformAdmin($data);
-				} else {
-					//门店收入后通知
-					//$data = [];
-					//InformAdminService::shopIncomeInformAdmin($data);
-				}
-				break;
-		}
-		$asset = self::updateByMerchantId($merchantId, $updateData);
-		//以下一定要排后面,否则数据不准确
-		if ($totalFee > 0) {
-			//xhStatIncomeService::replace($merchantId, $totalFee, $order['payWay']);
-			//xhStatIncomeMonthService::replace($merchantId, $totalFee, $order['payWay']);
-			/**收入来源资金增加**/
-			/*
-			StatIncomeSourceService::replaceData([
-				'merchantId' => $order['merchantId'],
-				'sourceType' => $order['sourceType'],
-				'amount' => $order['actPrice'],
-				'payWay' => $order['payWay']
-			]);
-			*/
-		}
-	}
-	
-	public static function add($data)
-	{
-		$return = xhMerchantAsset::add($data);
-		return $return;
-	}
-	
-	public static function withdraw()
-	{
-		$all = xhMerchantService::getAllByCondition(['status' => 1]);
-		if (empty($all)) {
-			return false;
-		}
-		foreach ($all as $merchant) {
-			$connection = Yii::$app->db;//事务处理
-			$transaction = $connection->beginTransaction();
-			try {
-				$merchantId = $merchant['id'];
-				$merchantAsset = self::getByMerchantId($merchantId);
-				$amount = $merchantAsset['balance'];
-				if ($amount <= 0) {
-					Yii::info('余额不足');
-					return false;
-				}
-				$mBalance = stringUtil::calcSub($merchantAsset['balance'], $amount);
-				$newFreezeBalance = stringUtil::calcAdd($merchantAsset['freezeBalance'], $amount);
-				$date = date("Y-m-d H:i:s");
-				
-				$id = stringUtil::generateMerchantCashOrderNo($merchantId);
-				$cashData = ['id' => $id, 'amount' => $amount, 'merchantId' => $merchantId, 'balance' => $mBalance, 'addTime' => time(), 'createTime' => $date];
-				$order = xhDrawCashService::add($cashData);
-				$orderId = $order['id'];
-				xhMerchantAssetService::updateByMerchantId($merchantId, ['balance' => $mBalance, 'freezeBalance' => $newFreezeBalance]);
-				
-				$now = time();
-				$capitalTypeArray = configDict::getConfig('capitalType', 'xhDrawCash');
-				$capitalType = $capitalTypeArray['id'];
-				$mIncome = $merchantAsset['totalIncome'];
-				$mExpend = $merchantAsset['totalExpend'];
-				$payWay = configDict::getConfig('payWay', 'other');
-				$capitalData = [
-					'relateId' => (string)$orderId,
-					'balance' => $mBalance,
-					'totalIncome' => $mIncome,
-					'totalExpend' => $mExpend,
-					'amount' => $amount,
-					'io' => 0,
-					'payWay' => $payWay,
-					'event' => '申请提现',
-					'merchantId' => $merchantId,
-					'userId' => 0,
-					'userName' => '',
-					'alipayId' => '',
-					'affectBalance' => 1,//会影响商家的余额
-					'createTime' => $date,
-					'addTime' => $now,
-					'capitalType' => $capitalType,
-					'operateId' => 0,
-				];
-				xhMerchantCapitalService::add($capitalData);//商家资金流水记录增加
+
+    public static function getByMerchantId($id)
+    {
+        $condition = ['merchantId' => $id];
+        $merchant = xhMerchantAsset::getByCondition($condition);
+        return $merchant;
+    }
+
+    /**
+     * 资产初始化,计算总量保存到xhMerchantAsset
+     */
+    public static function assetInit($merchantId)
+    {
+        set_time_limit(0);
+        //计算总收入
+        $income = Yii::$app->db->createCommand("SELECT SUM(amount) as totalIncome FROM xhMerchantCapital WHERE io=1 and merchantId={$merchantId}")->queryOne();
+        $totalIncome = $income['totalIncome'];
+        //计算总粉丝数
+        $totalFans = xhUser::find()->andWhere(['subscribe' => 1, 'merchantId' => $merchantId])->count('id');
+        //计算访问总量
+        $visit = Yii::$app->db->createCommand("SELECT SUM(riseNum) as num FROM xhStatVisitByDay WHERE merchantId={$merchantId}")->queryOne();
+        $totalVisit = $visit['num'];
+        //计算总交易量
+        $totalDeal = xhMerchantCapital::find()->andWhere(['io' => 1, 'merchantId' => $merchantId])->count('id');
+        $data = ['totalDeal' => $totalDeal, 'totalVisit' => $totalVisit, 'totalFans' => $totalFans, 'totalIncome' => $totalIncome];
+        self::updateByMerchantId($merchantId, $data);
+    }
+
+    public static function updateByMerchantId($merchantId, $data)
+    {
+        xhMerchantAsset::updateByCondition(['merchantId' => $merchantId], $data);
+        return self::refreshByMerchantId($merchantId);
+    }
+
+    public static function refreshByMerchantId($merchantId)
+    {
+        $key = configDict::getCacheKey('merchantAsset') . $merchantId;
+        Yii::$app->redis->executeCommand('DEL', [$key]);
+        return self::getByMerchantId($merchantId);
+    }
+
+    //收入后资产变更 shish 2019.12.24
+    public static function incomeChangeAsset($merchant, $merchantAsset, $updateData, $order, $capitalType)
+    {
+        $merchantId = $merchant['id'];
+        $openMerchant = xhWxOpenService::getMerchant();
+        $openMerchantId = $openMerchant['id'];
+        $orderId = $order['id'];
+        $date = date("Y-m-d H:i");
+        $totalFee = 0;
+        $payWayList = configDict::getConfig('payWayName');
+        $payWay = isset($order['payWay']) ? $order['payWay'] : 0;
+        $payWay = $payWayList[$payWay];
+        $userId = isset($order['userId']) ? $order['userId'] : 0;
+        $user = xhUserService::getById($userId);
+        $userName = isset($user['userName']) ? $user['userName'] : '游客';
+        //充值支付涉及的流水类型列表
+        $typeList = configDict::getConfig('capitalType');
+        //根据流水类型定制通知内容
+        switch ($capitalType) {
+            //购买商品
+            case $typeList['xhOrder']['id']:
+                $orderName = $order['bookName'];
+                $totalFee = $order['actPrice'];
+                $goodsList = xhOrderGoodsService::getAllByOrderId($orderId);
+                if (!empty($goodsList)) {
+                    foreach ($goodsList as $goodsKey => $goodsVal) {
+                        $goodsId = $goodsVal['goodsId'];
+                        $goods = xhGoodsService::getById($goodsId);
+                        if (!empty($goods)) {
+                            $actualSold = stringUtil::calcAdd($goods['actualSold'], 1);
+                            xhGoodsService::updateById($goodsId, ['actualSold' => $actualSold]);//商品被售出数量+1
+                        }
+                    }
+                }
+                if ($order['sourceType'] == 0) {
+                    //商城下单后通知
+                    //$data = [];
+                    //InformAdminService::goodsSoldInformAdmin($data);
+                } else {
+                    //门店收入后通知
+                    //$data = [];
+                    //InformAdminService::shopIncomeInformAdmin($data);
+                }
+                break;
+        }
+        $asset = self::updateByMerchantId($merchantId, $updateData);
+        //以下一定要排后面,否则数据不准确
+        if ($totalFee > 0) {
+            xhStatIncomeService::replace($merchantId, $totalFee, $order['payWay']);
+            xhStatIncomeMonthService::replace($merchantId, $totalFee, $order['payWay']);
+            /**收入来源资金增加**/
+            StatIncomeSourceService::replaceData([
+                'merchantId' => $order['merchantId'],
+                'sourceType' => $order['sourceType'],
+                'amount' => $order['actPrice'],
+                'payWay' => $order['payWay']
+            ]);
+        }
+    }
+
+    public static function add($data)
+    {
+        $return = xhMerchantAsset::add($data);
+        return $return;
+    }
+
+    public static function withdraw()
+    {
+        $all = xhMerchantService::getAllByCondition(['status' => 1]);
+        if (empty($all)) {
+            return false;
+        }
+        foreach ($all as $merchant) {
+            $connection = Yii::$app->db;//事务处理
+            $transaction = $connection->beginTransaction();
+            try {
+                $merchantId = $merchant['id'];
+                $merchantAsset = self::getByMerchantId($merchantId);
+                $amount = $merchantAsset['balance'];
+                if ($amount <= 0) {
+                    Yii::info('余额不足');
+                    return false;
+                }
+                $mBalance = stringUtil::calcSub($merchantAsset['balance'], $amount);
+                $newFreezeBalance = stringUtil::calcAdd($merchantAsset['freezeBalance'], $amount);
+                $date = date("Y-m-d H:i:s");
+
+                $id = stringUtil::generateMerchantCashOrderNo($merchantId);
+                $cashData = ['id' => $id, 'amount' => $amount, 'merchantId' => $merchantId, 'balance' => $mBalance, 'addTime' => time(), 'createTime' => $date];
+                $order = xhDrawCashService::add($cashData);
+                $orderId = $order['id'];
+                xhMerchantAssetService::updateByMerchantId($merchantId, ['balance' => $mBalance, 'freezeBalance' => $newFreezeBalance]);
+
+                $now = time();
+                $capitalTypeArray = configDict::getConfig('capitalType', 'xhDrawCash');
+                $capitalType = $capitalTypeArray['id'];
+                $mIncome = $merchantAsset['totalIncome'];
+                $mExpend = $merchantAsset['totalExpend'];
+                $payWay = configDict::getConfig('payWay', 'other');
+                $capitalData = [
+                    'relateId' => (string)$orderId,
+                    'balance' => $mBalance,
+                    'totalIncome' => $mIncome,
+                    'totalExpend' => $mExpend,
+                    'amount' => $amount,
+                    'io' => 0,
+                    'payWay' => $payWay,
+                    'event' => '申请提现',
+                    'merchantId' => $merchantId,
+                    'userId' => 0,
+                    'userName' => '',
+                    'alipayId' => '',
+                    'affectBalance' => 1,//会影响商家的余额
+                    'createTime' => $date,
+                    'addTime' => $now,
+                    'capitalType' => $capitalType,
+                    'operateId' => 0,
+                ];
+                xhMerchantCapitalService::add($capitalData);//商家资金流水记录增加
 
 //				xhCommonService::sendMobileMsg('15280215347', '有客户申请提现,请及时处理');
-				
-				$id = $orderId;
-				$draw = xhDrawCashService::getById($id);
-				$drawAmount = isset($draw['amount']) ? floatval($draw['amount']) : 0;
-				if ($draw['status'] == 1) {
-					Yii::info('已经完成转账,请不要重复请求!');
-					return;
-				}
-				$merchantId = isset($draw['merchantId']) ? $draw['merchantId'] : 0;
-				//$admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
-				$time = strtotime(date("Y-m-d"));
-				$income = xhStatIncomeService::getByIds($merchantId, $time);
-				$amount = isset($income['amount']) ? $income['amount'] : 0;
-				$merchantExtInfo = xhMerchantExtendService::getByMerchantId($merchantId);//取支付宝帐号
-				
-				$asset = xhMerchantAssetService::getByMerchantId($merchantId);
-				
-				if ($merchantExtInfo['alipayAccount'] == '') {
-					Yii::info('转账接收方的支付宝帐号为空');
-					return;
-				}
-				if ($drawAmount == 0) {
-					Yii::info('转账金额为0');
-					return;
-				}
-				$alipayWap = Yii::getAlias("@vendor/alipayWap");
-				require_once($alipayWap . '/aop/AopClient.php');
-				require_once($alipayWap . '/aop/request/AlipayFundTransToaccountTransferRequest.php');
-				
-				//require_once($alipayWap . '/config.php');
-				$config = array(
-					//应用ID,您的APPID。
-					'app_id' => "2017041906821571",
-					
-					//商户私钥,您的原始格式RSA私钥
-					'merchant_private_key' => "MIIEpAIBAAKCAQEAvbeu6o90L+0AilI+mbhuJJH0lUv7hWQCEC+XUc+cWlC9ulKC3cSVScVLJHpUc09aj6v/iD1p9iVfgMxjeADNVKiQC2RJyRshAjzyTq+2bTcODp619iV2y4qW8UM65VcP7Ide3P0uT5xC2ReW0HpkdHZgm4F+P7mh1VhGt9qOP3hjvoraAHhtGACvsGvy8H69HhSAG+CEmFt7f2tKNWJ8xEUvkfhDvys93PfTk4xMWj048hJE2r38+2mWI/Il5dFQHWXXTVl2x9yi7uhEEW42a+7s9Q3HgqEvZiQ2NI1FTeEAPLFBApiEsNLY/smaszwqqfWGAyTMvtQ6T4K96GcTLQIDAQABAoIBAHwYTj33n9RJfnT73x7F2KXrIsUVcmyKQh88QgqtdmRNNA1QM3HESLJ8bu5pZhwW5/HaW8dOBKWRRKsHBnlUbPrXV4FcFDeLm0fPfd+iZ/2AaZ1+ix962f3BpYIiq7+f9zaMRazfnw9L8x31pByyMktLs12EkoQ0dHsMxxUzzKAOiiPnvCn8Pv+Jb2qej8GXgCjefutCVNMWGsdwJtMVXEbpdmMa48Wvw+0In5ZS/UG39YAreFzgDqI9jWHE1ZhkGmB1+8hKpeIlEeVGAeYVveUgssMORdA/YY8SWHk26KSIFXBrmdKjAcRJ8Q7ZHUmzIqAV+IMV+RD4J5mZHeJgdAECgYEA8J+Hp1M6eYbT4CPLXa//yRP6Xo+qSzrKHaRB1LRAjYhvKpx/TQetYpNCJ5bWpa+Jp0T5R21pzuYaJkPuGlNEHA13b5T3r1l2ltomSEdaShvD5EZ9WtErYV5zpSv7FjjIGkbwa0H3A8Ydnvw5z4A9TZjjHLjC2GtVGJReqHGglMECgYEAydddA4NRPxmXvIjjmLb1Ft1qwHuyv3vvWhi50foGZXNEnBcfP/OkfyBDDpOEu34GZBMXK9ykHBs1l93OEFGXh7AwW0Lp5lARahBEfBZgPjq5yPO8TOJZrb5hVcuvoDdGjxpRh93XDnQDhWS/1IvUcBLcIsTcnVvfrkX4NLxF/W0CgYEAxamG+gD4rBQBwMImsRN+/2MV7M//iEUG+0qPeXeI/7rv9wUP3etMlwl48qSKNxj37xxN2ksa/Acxu/VZhu6XqKO3VUX+IWFQdaNGh2F13iLozIDLQOtKw3WfcjOq0xpZ5pwXq0RI8iSw+IUhyD8EHNZW2qU8CiRBhyt6hsywqQECgYBa8+06FAachI/XqWfF/UvcDdJ5AkS9/L8SvmmdsSkItjSIkfLHAqdxkbwl6Vu6kUOX/PJIFZjuAWTZFl4xBFNgFYj01uZHnnT6cnIp6HteD2CAqTSFAMqgfFWoL6zoaYAmJBnxO4oZPTYI+ilnQcts5VLFaChx0GCvS2BZgy2W0QKBgQDjP2VtRq4aVSLUq2z1KIDI7GJBbOM5KSW1OEj4sfEdViozPh3Ar/FQWiij1oCZF+iJdKkonHoDbDd+Q0ykcpQ+5Gv07iiT8wJYFR/0j8g2kfql7bVQhGSBeBMS5sawKR3CvkfW73WX+CNnf0PklTY0kTyt6WRXDnKSeyxFVwSZ7g==",
-					
-					//异步通知地址
-					'notify_url' => Yii::$app->params['frontUrl'] . "/notice/alipay-async",
-					
-					//同步跳转
-					'return_url' => "",
-					
-					//编码格式
-					'charset' => "UTF-8",
-					
-					//签名方式
-					'sign_type' => "RSA2",
-					
-					//支付宝网关
-					'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
-					
-					//支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
-					'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsz3m9juAR1xew4DY6c34gvbwNg8pZ92f932tseKs+4+pF0e+jTDiUo/xHImNDi1KXt1B+s3LxY9L/sxEksbavwmhgbz/igN1cAEwS2YM+Gnf0csDrxAPJhoKL5FTwxPEQ/8VSgroU+6GlF3LAx4VHa1qfn5MqRPfLroJcyPDyGfNe9vna2FnO4E/PH+hVbvPUAwX3XrUvJIm4OgY0JE3HYFlu+O7F4Ln6+Sl+Zv/ZE2nZAvNiyAwW5iVKhKXLieExqwd0NdrP28baBqkkIY+tmV7butGjB52iK1UbU0+1uiaPL4xBxRy6d0LZmYlvdVHp0JRUuwxBLChGgOCo/76DQIDAQAB",
-				
-				);
-				
-				$aop = new \AopClient();
-				$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
-				$aop->appId = $config['app_id'];
-				$aop->rsaPrivateKey = $config['merchant_private_key'];
-				$aop->alipayrsaPublicKey = $config['alipay_public_key'];
-				$aop->apiVersion = '1.0';
-				$aop->signType = 'RSA2';
-				$aop->postCharset = 'UTF-8';
-				$aop->format = 'json';
-				$request = new \AlipayFundTransToaccountTransferRequest ();
-				$request->setBizContent("{" .
-					"\"out_biz_no\":\"" . $id . "\"," .
-					"\"payee_type\":\"ALIPAY_LOGONID\"," .
-					"\"payee_account\":\"" . $merchantExtInfo['alipayAccount'] . "\"," .
-					"\"amount\":\"" . $drawAmount . "\"," .
-					"\"payee_real_name\":\"" . $merchantExtInfo['alipayAccountName'] . "\"," .
-					"\"payer_show_name\":\"厦门中花汇信息科技有限公司\"," .
-					"\"remark\":\"提现申请\"" .
-					"  }");
-				$result = $aop->execute($request);
-				$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
-				$resultCode = $result->$responseNode->code;
-				$returnOrderId = $result->$responseNode->order_id;
-				if (!empty($resultCode) && $resultCode == 10000) {
-					xhDrawCashService::updateById($id, ['thirdSerialNumber' => $returnOrderId, 'status' => 1]);
-					$remainAmount = stringUtil::calcSub($asset['freezeBalance'], $drawAmount);
-					xhMerchantAssetService::updateByMerchantId($merchantId, ['freezeBalance' => $remainAmount]);
-					$transaction->commit();
-					/*
-					$openId = $admin['openId'];
-					$openMerchant = xhWxOpenService::getMerchant();//取平台绑定的商家
-					$openMerchantId = $openMerchant['id'];
-					$allTM = xhTMessageService::getList($openMerchantId);
-					$shortTempId = 'OPENTM201319876';
-					if(isset($allTM[$shortTempId])){
-					$tempId =  $allTM[$shortTempId];
-					$data = [
-						"touser" => $openId,
-						"template_id" => $tempId,
-						"url" => Yii::$app->params['adminUrl'] . '/draw-cash/list',
-						"data" => [
-							"first" => ["value" => '已经完成结算。', "color" => "#173177"],
-							"keyword1" => ["value" => '当天', "color" => "#173177"],
-							"keyword2" => ["value" => $amount . '元', "color" => "#173177"],
-							"remark" => ["value" => "支付宝收入:{$drawAmount}元,已汇入您的帐户。\n点击查看结算记录", "color" => "#173177"]
-						]
-					];
-					}
-					wxUtil::sendTaskInform($data, $openMerchant);
-					*/
-					//xhCommonService::sendMobileMsg($admin['mobile'], "您的提现金额:{$drawAmount}元已经到帐,请注意查收。");
-				} else {
-					$msg = $result->$responseNode->msg;
-					$sub_code = $result->$responseNode->sub_code;
-					$sub_msg = $result->$responseNode->sub_msg;
-					Yii::info("转帐失败,原因:code:" . $resultCode . " msg:" . $msg . " sub_code:" . $sub_code . " sub_msg:" . $sub_msg);
-					$transaction->rollBack();
-				}
-			} catch (Exception $e) {
-				$transaction->rollBack();
-			}
-		}
-		
-	}
+
+                $id = $orderId;
+                $draw = xhDrawCashService::getById($id);
+                $drawAmount = isset($draw['amount']) ? floatval($draw['amount']) : 0;
+                if ($draw['status'] == 1) {
+                    Yii::info('已经完成转账,请不要重复请求!');
+                    return;
+                }
+                $merchantId = isset($draw['merchantId']) ? $draw['merchantId'] : 0;
+                //$admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
+                $time = strtotime(date("Y-m-d"));
+                $income = xhStatIncomeService::getByIds($merchantId, $time);
+                $amount = isset($income['amount']) ? $income['amount'] : 0;
+                $merchantExtInfo = xhMerchantExtendService::getByMerchantId($merchantId);//取支付宝帐号
+
+                $asset = xhMerchantAssetService::getByMerchantId($merchantId);
+
+                if ($merchantExtInfo['alipayAccount'] == '') {
+                    Yii::info('转账接收方的支付宝帐号为空');
+                    return;
+                }
+                if ($drawAmount == 0) {
+                    Yii::info('转账金额为0');
+                    return;
+                }
+                $alipayWap = Yii::getAlias("@vendor/alipayWap");
+                require_once($alipayWap . '/aop/AopClient.php');
+                require_once($alipayWap . '/aop/request/AlipayFundTransToaccountTransferRequest.php');
+
+                //require_once($alipayWap . '/config.php');
+                $config = array(
+                    //应用ID,您的APPID。
+                    'app_id' => "2017041906821571",
+
+                    //商户私钥,您的原始格式RSA私钥
+                    'merchant_private_key' => "MIIEpAIBAAKCAQEAvbeu6o90L+0AilI+mbhuJJH0lUv7hWQCEC+XUc+cWlC9ulKC3cSVScVLJHpUc09aj6v/iD1p9iVfgMxjeADNVKiQC2RJyRshAjzyTq+2bTcODp619iV2y4qW8UM65VcP7Ide3P0uT5xC2ReW0HpkdHZgm4F+P7mh1VhGt9qOP3hjvoraAHhtGACvsGvy8H69HhSAG+CEmFt7f2tKNWJ8xEUvkfhDvys93PfTk4xMWj048hJE2r38+2mWI/Il5dFQHWXXTVl2x9yi7uhEEW42a+7s9Q3HgqEvZiQ2NI1FTeEAPLFBApiEsNLY/smaszwqqfWGAyTMvtQ6T4K96GcTLQIDAQABAoIBAHwYTj33n9RJfnT73x7F2KXrIsUVcmyKQh88QgqtdmRNNA1QM3HESLJ8bu5pZhwW5/HaW8dOBKWRRKsHBnlUbPrXV4FcFDeLm0fPfd+iZ/2AaZ1+ix962f3BpYIiq7+f9zaMRazfnw9L8x31pByyMktLs12EkoQ0dHsMxxUzzKAOiiPnvCn8Pv+Jb2qej8GXgCjefutCVNMWGsdwJtMVXEbpdmMa48Wvw+0In5ZS/UG39YAreFzgDqI9jWHE1ZhkGmB1+8hKpeIlEeVGAeYVveUgssMORdA/YY8SWHk26KSIFXBrmdKjAcRJ8Q7ZHUmzIqAV+IMV+RD4J5mZHeJgdAECgYEA8J+Hp1M6eYbT4CPLXa//yRP6Xo+qSzrKHaRB1LRAjYhvKpx/TQetYpNCJ5bWpa+Jp0T5R21pzuYaJkPuGlNEHA13b5T3r1l2ltomSEdaShvD5EZ9WtErYV5zpSv7FjjIGkbwa0H3A8Ydnvw5z4A9TZjjHLjC2GtVGJReqHGglMECgYEAydddA4NRPxmXvIjjmLb1Ft1qwHuyv3vvWhi50foGZXNEnBcfP/OkfyBDDpOEu34GZBMXK9ykHBs1l93OEFGXh7AwW0Lp5lARahBEfBZgPjq5yPO8TOJZrb5hVcuvoDdGjxpRh93XDnQDhWS/1IvUcBLcIsTcnVvfrkX4NLxF/W0CgYEAxamG+gD4rBQBwMImsRN+/2MV7M//iEUG+0qPeXeI/7rv9wUP3etMlwl48qSKNxj37xxN2ksa/Acxu/VZhu6XqKO3VUX+IWFQdaNGh2F13iLozIDLQOtKw3WfcjOq0xpZ5pwXq0RI8iSw+IUhyD8EHNZW2qU8CiRBhyt6hsywqQECgYBa8+06FAachI/XqWfF/UvcDdJ5AkS9/L8SvmmdsSkItjSIkfLHAqdxkbwl6Vu6kUOX/PJIFZjuAWTZFl4xBFNgFYj01uZHnnT6cnIp6HteD2CAqTSFAMqgfFWoL6zoaYAmJBnxO4oZPTYI+ilnQcts5VLFaChx0GCvS2BZgy2W0QKBgQDjP2VtRq4aVSLUq2z1KIDI7GJBbOM5KSW1OEj4sfEdViozPh3Ar/FQWiij1oCZF+iJdKkonHoDbDd+Q0ykcpQ+5Gv07iiT8wJYFR/0j8g2kfql7bVQhGSBeBMS5sawKR3CvkfW73WX+CNnf0PklTY0kTyt6WRXDnKSeyxFVwSZ7g==",
+
+                    //异步通知地址
+                    'notify_url' => Yii::$app->params['frontUrl'] . "/notice/alipay-async",
+
+                    //同步跳转
+                    'return_url' => "",
+
+                    //编码格式
+                    'charset' => "UTF-8",
+
+                    //签名方式
+                    'sign_type' => "RSA2",
+
+                    //支付宝网关
+                    'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
+
+                    //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
+                    'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsz3m9juAR1xew4DY6c34gvbwNg8pZ92f932tseKs+4+pF0e+jTDiUo/xHImNDi1KXt1B+s3LxY9L/sxEksbavwmhgbz/igN1cAEwS2YM+Gnf0csDrxAPJhoKL5FTwxPEQ/8VSgroU+6GlF3LAx4VHa1qfn5MqRPfLroJcyPDyGfNe9vna2FnO4E/PH+hVbvPUAwX3XrUvJIm4OgY0JE3HYFlu+O7F4Ln6+Sl+Zv/ZE2nZAvNiyAwW5iVKhKXLieExqwd0NdrP28baBqkkIY+tmV7butGjB52iK1UbU0+1uiaPL4xBxRy6d0LZmYlvdVHp0JRUuwxBLChGgOCo/76DQIDAQAB",
+
+                );
+
+                $aop = new \AopClient();
+                $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
+                $aop->appId = $config['app_id'];
+                $aop->rsaPrivateKey = $config['merchant_private_key'];
+                $aop->alipayrsaPublicKey = $config['alipay_public_key'];
+                $aop->apiVersion = '1.0';
+                $aop->signType = 'RSA2';
+                $aop->postCharset = 'UTF-8';
+                $aop->format = 'json';
+                $request = new \AlipayFundTransToaccountTransferRequest ();
+                $request->setBizContent("{" .
+                    "\"out_biz_no\":\"" . $id . "\"," .
+                    "\"payee_type\":\"ALIPAY_LOGONID\"," .
+                    "\"payee_account\":\"" . $merchantExtInfo['alipayAccount'] . "\"," .
+                    "\"amount\":\"" . $drawAmount . "\"," .
+                    "\"payee_real_name\":\"" . $merchantExtInfo['alipayAccountName'] . "\"," .
+                    "\"payer_show_name\":\"厦门中花汇信息科技有限公司\"," .
+                    "\"remark\":\"提现申请\"" .
+                    "  }");
+                $result = $aop->execute($request);
+                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
+                $resultCode = $result->$responseNode->code;
+                $returnOrderId = $result->$responseNode->order_id;
+                if (!empty($resultCode) && $resultCode == 10000) {
+                    xhDrawCashService::updateById($id, ['thirdSerialNumber' => $returnOrderId, 'status' => 1]);
+                    $remainAmount = stringUtil::calcSub($asset['freezeBalance'], $drawAmount);
+                    xhMerchantAssetService::updateByMerchantId($merchantId, ['freezeBalance' => $remainAmount]);
+                    $transaction->commit();
+                    /*
+                    $openId = $admin['openId'];
+                    $openMerchant = xhWxOpenService::getMerchant();//取平台绑定的商家
+                    $openMerchantId = $openMerchant['id'];
+                    $allTM = xhTMessageService::getList($openMerchantId);
+                    $shortTempId = 'OPENTM201319876';
+                    if(isset($allTM[$shortTempId])){
+                    $tempId =  $allTM[$shortTempId];
+                    $data = [
+                        "touser" => $openId,
+                        "template_id" => $tempId,
+                        "url" => Yii::$app->params['adminUrl'] . '/draw-cash/list',
+                        "data" => [
+                            "first" => ["value" => '已经完成结算。', "color" => "#173177"],
+                            "keyword1" => ["value" => '当天', "color" => "#173177"],
+                            "keyword2" => ["value" => $amount . '元', "color" => "#173177"],
+                            "remark" => ["value" => "支付宝收入:{$drawAmount}元,已汇入您的帐户。\n点击查看结算记录", "color" => "#173177"]
+                        ]
+                    ];
+                    }
+                    wxUtil::sendTaskInform($data, $openMerchant);
+                    */
+                    //xhCommonService::sendMobileMsg($admin['mobile'], "您的提现金额:{$drawAmount}元已经到帐,请注意查收。");
+                } else {
+                    $msg = $result->$responseNode->msg;
+                    $sub_code = $result->$responseNode->sub_code;
+                    $sub_msg = $result->$responseNode->sub_msg;
+                    Yii::info("转帐失败,原因:code:" . $resultCode . " msg:" . $msg . " sub_code:" . $sub_code . " sub_msg:" . $sub_msg);
+                    $transaction->rollBack();
+                }
+            } catch (Exception $e) {
+                $transaction->rollBack();
+            }
+        }
+
+    }
 }

+ 106 - 98
common/services/xhStatIncomeMonthService.php

@@ -9,102 +9,110 @@ use common\components\configDict;
 
 class xhStatIncomeMonthService
 {
-	
-	/**
-	 * 添加与更新
-	 */
-	public static function replace($merchantId, $totalFee, $payWay)
-	{
-		$year = date("Y");
-		$month = date("n");
-		$income = self::getByIds($merchantId, $year, $month);
-		$weixin = 0;
-		$alipay = 0;
-		$balancePay = 0;
-		$cash = 0;
-		$addTime = time();
-		
-		$payList = configDict::getConfig('payWay');
-		if ($payList['weixinPay'] == $payWay) {
-			$weixin = $totalFee;
-		} elseif ($payWay == $payList['alipay']) {
-			$alipay = $totalFee;
-		} elseif ($payWay == $payList['balancePay']) {
-			$balancePay = $totalFee;
-		} elseif ($payWay == $payList['cashPay']) {
-			$cash = $totalFee;
-		} elseif ($payWay == $payList['mini']) {
-			$weixin = $totalFee;
-		}
-		
-		if (empty($income)) {
-			$data = ['year' => $year,
-				'month' => $month,
-				'amount' => $totalFee,
-				'merchantId' => $merchantId,
-				'addTime' => $addTime,
-				'weixin' => $weixin,
-				'alipay' => $alipay,
-				'balancePay' => $balancePay,
-				'cash' => $cash,
-			];
-			self::add($data);
-		} else {
-			$amount = stringUtil::calcAdd($income['amount'], $totalFee);
-			$weixin = stringUtil::calcAdd($income['weixin'], $weixin);
-			$cash = stringUtil::calcAdd($income['cash'], $cash);
-			$balancePay = stringUtil::calcAdd($income['balancePay'], $balancePay);
-			$alipay = stringUtil::calcAdd($income['alipay'], $alipay);
-			$data = [
-				'amount' => $amount,
-				'weixin' => $weixin,
-				'alipay' => $alipay,
-				'balancePay' => $balancePay,
-				'cash' => $cash,
-			];
-			self::updateByIds($merchantId, $year, $month, $data);
-		}
-	}
-	
-	public static function updateByIds($merchantId, $year, $month, $data)
-	{
-		xhStatIncomeMonth::updateByCondition(['year' => $year, 'month' => $month, 'merchantId' => $merchantId], $data);
-		self::getByIds($merchantId, $year, $month);
-		$cacheKey = configDict::getCacheKey('xhStatIncomeMonth') . '_' . $merchantId . '_' . $year . '_' . $month;
-		$params = [$cacheKey];
-		if (!empty($data)) {
-			foreach ($data as $key => $val) {
-				$params[] = $key;
-				$params[] = $val;
-			}
-		}
-		Yii::$app->redis->executeCommand('HMSET', $params);
-		return self::getByIds($merchantId, $year, $month);
-	}
-	
-	public static function add($data)
-	{
-		$return = xhStatIncomeMonth::add($data);
-		return $return;
-	}
-	
-	public static function getByIds($merchantId, $year, $month)
-	{
-		$income = xhStatIncomeMonth::find()->where(['merchantId' => $merchantId, 'year' => $year, 'month' => $month])->asArray()->one();
-		return $income;
-	}
-	
-	/**
-	 * 获取本月收入
-	 */
-	public static function getMonthIncome($merchantId, $year, $month)
-	{
-		$income = self::getByIds($merchantId, $year, $month);
-		$amount = 0;
-		if (!empty($income)) {
-			$amount = $income['amount'];
-		}
-		return $amount;
-	}
-	
+
+    /**
+     * 添加与更新
+     */
+    public static function replace($merchantId, $totalFee, $payWay)
+    {
+        $year = date("Y");
+        $month = date("n");
+        $time = date("Ym");
+        $income = self::getByTime($merchantId, $time);
+        $weixin = 0;
+        $alipay = 0;
+        $balancePay = 0;
+        $cash = 0;
+        $addTime = time();
+
+        $payList = configDict::getConfig('payWay');
+        if ($payList['weixinPay'] == $payWay) {
+            $weixin = $totalFee;
+        } elseif ($payWay == $payList['alipay']) {
+            $alipay = $totalFee;
+        } elseif ($payWay == $payList['balancePay']) {
+            $balancePay = $totalFee;
+        } elseif ($payWay == $payList['cashPay']) {
+            $cash = $totalFee;
+        } elseif ($payWay == $payList['mini']) {
+            $weixin = $totalFee;
+        }
+
+        if (empty($income)) {
+            $data = ['year' => $year,
+                'month' => $month,
+                'time' => $time,
+                'amount' => $totalFee,
+                'merchantId' => $merchantId,
+                'addTime' => $addTime,
+                'weixin' => $weixin,
+                'alipay' => $alipay,
+                'balancePay' => $balancePay,
+                'cash' => $cash,
+            ];
+            self::add($data);
+        } else {
+            $amount = stringUtil::calcAdd($income['amount'], $totalFee);
+            $weixin = stringUtil::calcAdd($income['weixin'], $weixin);
+            $cash = stringUtil::calcAdd($income['cash'], $cash);
+            $balancePay = stringUtil::calcAdd($income['balancePay'], $balancePay);
+            $alipay = stringUtil::calcAdd($income['alipay'], $alipay);
+            $data = [
+                'amount' => $amount,
+                'weixin' => $weixin,
+                'alipay' => $alipay,
+                'balancePay' => $balancePay,
+                'cash' => $cash,
+            ];
+            self::updateByIds($merchantId, $year, $month, $data);
+        }
+    }
+
+    public static function updateByIds($merchantId, $year, $month, $data)
+    {
+        xhStatIncomeMonth::updateByCondition(['year' => $year, 'month' => $month, 'merchantId' => $merchantId], $data);
+        self::getByIds($merchantId, $year, $month);
+        $cacheKey = configDict::getCacheKey('xhStatIncomeMonth') . '_' . $merchantId . '_' . $year . '_' . $month;
+        $params = [$cacheKey];
+        if (!empty($data)) {
+            foreach ($data as $key => $val) {
+                $params[] = $key;
+                $params[] = $val;
+            }
+        }
+        Yii::$app->redis->executeCommand('HMSET', $params);
+        return self::getByIds($merchantId, $year, $month);
+    }
+
+    public static function add($data)
+    {
+        $return = xhStatIncomeMonth::add($data);
+        return $return;
+    }
+
+    public static function getByIds($merchantId, $year, $month)
+    {
+        $income = xhStatIncomeMonth::find()->where(['merchantId' => $merchantId, 'year' => $year, 'month' => $month])->asArray()->one();
+        return $income;
+    }
+
+    public static function getByTime($merchantId, $time)
+    {
+        $income = xhStatIncomeMonth::find()->where(['merchantId' => $merchantId, 'time' => $time])->asArray()->one();
+        return $income;
+    }
+
+    /**
+     * 获取本月收入
+     */
+    public static function getMonthIncome($merchantId, $year, $month)
+    {
+        $income = self::getByIds($merchantId, $year, $month);
+        $amount = 0;
+        if (!empty($income)) {
+            $amount = $income['amount'];
+        }
+        return $amount;
+    }
+
 }