| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- <?php
- namespace common\services;
- use biz\sj\services\MerchantExtendService;
- use bizHd\message\services\InformAdminService;
- use bizHd\stat\services\StatIncomeCategoryService;
- use bizHd\stat\services\StatIncomeSourceService;
- use bizHd\wx\services\WxOpenService;
- use Yii;
- use common\components\dict;
- use common\components\stringUtil;
- use common\components\wxUtil;
- use common\services\xhGoodsService;
- use common\models\xhMerchantAsset;
- use common\models\xhUser;
- use common\models\xhSjCapital;
- use common\services\xhAdminService;
- use common\services\xhTMessageService;
- use common\services\xhOrderGoodsService;
- class xhMerchantAssetService
- {
- public static function getBySjId($id)
- {
- $condition = ['sjId' => $id];
- $merchant = xhMerchantAsset::getByCondition($condition);
- return $merchant;
- }
- /**
- * 资产初始化,计算总量保存到xhMerchantAsset
- */
- public static function assetInit($sjId)
- {
- set_time_limit(0);
- //计算总收入
- $income = Yii::$app->db->createCommand("SELECT SUM(amount) as totalIncome FROM xhSjCapital WHERE io=1 and sjId={$sjId}")->queryOne();
- $totalIncome = $income['totalIncome'];
- //计算总粉丝数
- $totalFans = xhUser::find()->andWhere(['subscribe' => 1, 'sjId' => $sjId])->count('id');
- //计算访问总量
- $visit = Yii::$app->db->createCommand("SELECT SUM(riseNum) as num FROM xhStatVisitByDay WHERE sjId={$sjId}")->queryOne();
- $totalVisit = $visit['num'];
- //计算总交易量
- $totalDeal = xhSjCapital::find()->andWhere(['io' => 1, 'sjId' => $sjId])->count('id');
- $data = ['totalDeal' => $totalDeal, 'totalVisit' => $totalVisit, 'totalFans' => $totalFans, 'totalIncome' => $totalIncome];
- self::updateBySjId($sjId, $data);
- }
- public static function updateBySjId($sjId, $data)
- {
- xhMerchantAsset::updateByCondition(['sjId' => $sjId], $data);
- return self::refreshByMerchantId($sjId);
- }
- public static function refreshByMerchantId($sjId)
- {
- $key = dict::getCacheKey('merchantAsset') . $sjId;
- Yii::$app->redis->executeCommand('DEL', [$key]);
- return self::getBySjId($sjId);
- }
- //收入后资产变更 ssh 2019.12.24
- public static function incomeChangeAsset($merchant, $merchantAsset, $shopId, $updateData, $order, $capitalType, $isRecharge = false)
- {
- $sjId = $merchant['id'];
- $orderId = $order['id'];
- $totalFee = 0;
- //根据流水类型定制通知内容
- switch ($capitalType) {
- //购买商品
- case dict::getDict('capitalType', 'xhOrder', 'id'):
- $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
- }
- }
- }
- //收入提醒 ssh 2020.1.30
- $params = [
- 'order' => $order,
- ];
- $type = 'income';
- InformAdminService::addInform($shopId, $type, $params);
- break;
- default:
- }
- self::updateBySjId($sjId, $updateData);
- if ($isRecharge == false) {
- //数据统计,以下一定要排后面,否则数据不准确
- xhStatIncomeService::replace($sjId, $totalFee, $order['payWay']);
- xhStatIncomeMonthService::replace($sjId, $totalFee, $order['payWay']);
- StatIncomeSourceService::replaceData([
- 'sjId' => $order['sjId'],
- 'sourceType' => $order['sourceType'],
- 'amount' => $totalFee,
- '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 {
- $sjId = $merchant['id'];
- $merchantAsset = self::getBySjId($sjId);
- $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($sjId);
- $cashData = ['id' => $id, 'amount' => $amount, 'sjId' => $sjId, 'balance' => $mBalance, 'addTime' => time(), 'createTime' => $date];
- $order = xhDrawCashService::add($cashData);
- $orderId = $order['id'];
- xhMerchantAssetService::updateBySjId($sjId, ['balance' => $mBalance, 'freezeBalance' => $newFreezeBalance]);
- $now = time();
- $capitalTypeArray = dict::getDict('capitalType', 'xhDrawCash');
- $capitalType = $capitalTypeArray['id'];
- $mIncome = $merchantAsset['totalIncome'];
- $mExpend = $merchantAsset['totalExpend'];
- $payWay = dict::getDict('payWay', 'other');
- $capitalData = [
- 'relateId' => (string)$orderId,
- 'balance' => $mBalance,
- 'totalIncome' => $mIncome,
- 'totalExpend' => $mExpend,
- 'amount' => $amount,
- 'io' => 0,
- 'payWay' => $payWay,
- 'event' => '申请提现',
- 'sjId' => $sjId,
- 'userId' => 0,
- 'userName' => '',
- 'alipayId' => '',
- 'affectBalance' => 1,//会影响商家的余额
- 'createTime' => $date,
- 'addTime' => $now,
- 'capitalType' => $capitalType,
- 'operateId' => 0,
- ];
- xhSjCapitalService::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;
- }
- $sjId = isset($draw['sjId']) ? $draw['sjId'] : 0;
- //$admin = xhAdminToMerchantService::getAdminByMerchantId($sjId);
- $time = strtotime(date("Y-m-d"));
- $income = xhStatIncomeService::getByIds($sjId, $time);
- $amount = isset($income['amount']) ? $income['amount'] : 0;
- $merchantExtInfo = xhMerchantExtendService::getBySjId($sjId);//取支付宝帐号
- $asset = xhMerchantAssetService::getBySjId($sjId);
- 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');
- $extend = MerchantExtendService::getBySjId($sjId);
- $config = [
- //应用ID,您的APPID。
- 'app_id' => $extend['alipayPId'],
- //商户私钥,您的原始格式RSA私钥
- 'merchant_private_key' => $extend['alipayKey'],
- //异步通知地址
- 'notify_url' => Yii::$app->params['frontUrl'] . "/notice/ali-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' => $extend['alipayPublicKey'],
- ];
- $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::updateBySjId($sjId, ['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();
- }
- }
- }
- }
|