xhMerchantAssetService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. namespace common\services;
  3. use biz\sj\services\MerchantExtendService;
  4. use bizHd\message\services\InformAdminService;
  5. use bizHd\stat\services\StatIncomeCategoryService;
  6. use bizHd\stat\services\StatIncomeSourceService;
  7. use bizHd\wx\services\WxOpenService;
  8. use Yii;
  9. use common\components\dict;
  10. use common\components\stringUtil;
  11. use common\components\wxUtil;
  12. use common\services\xhGoodsService;
  13. use common\models\xhMerchantAsset;
  14. use common\models\xhUser;
  15. use common\models\xhSjCapital;
  16. use common\services\xhAdminService;
  17. use common\services\xhTMessageService;
  18. use common\services\xhOrderGoodsService;
  19. class xhMerchantAssetService
  20. {
  21. public static function getBySjId($id)
  22. {
  23. $condition = ['sjId' => $id];
  24. $merchant = xhMerchantAsset::getByCondition($condition);
  25. return $merchant;
  26. }
  27. /**
  28. * 资产初始化,计算总量保存到xhMerchantAsset
  29. */
  30. public static function assetInit($sjId)
  31. {
  32. set_time_limit(0);
  33. //计算总收入
  34. $income = Yii::$app->db->createCommand("SELECT SUM(amount) as totalIncome FROM xhSjCapital WHERE io=1 and sjId={$sjId}")->queryOne();
  35. $totalIncome = $income['totalIncome'];
  36. //计算总粉丝数
  37. $totalFans = xhUser::find()->andWhere(['subscribe' => 1, 'sjId' => $sjId])->count('id');
  38. //计算访问总量
  39. $visit = Yii::$app->db->createCommand("SELECT SUM(riseNum) as num FROM xhStatVisitByDay WHERE sjId={$sjId}")->queryOne();
  40. $totalVisit = $visit['num'];
  41. //计算总交易量
  42. $totalDeal = xhSjCapital::find()->andWhere(['io' => 1, 'sjId' => $sjId])->count('id');
  43. $data = ['totalDeal' => $totalDeal, 'totalVisit' => $totalVisit, 'totalFans' => $totalFans, 'totalIncome' => $totalIncome];
  44. self::updateBySjId($sjId, $data);
  45. }
  46. public static function updateBySjId($sjId, $data)
  47. {
  48. xhMerchantAsset::updateByCondition(['sjId' => $sjId], $data);
  49. return self::refreshByMerchantId($sjId);
  50. }
  51. public static function refreshByMerchantId($sjId)
  52. {
  53. $key = dict::getCacheKey('merchantAsset') . $sjId;
  54. Yii::$app->redis->executeCommand('DEL', [$key]);
  55. return self::getBySjId($sjId);
  56. }
  57. //收入后资产变更 ssh 2019.12.24
  58. public static function incomeChangeAsset($merchant, $merchantAsset, $shopId, $updateData, $order, $capitalType, $isRecharge = false)
  59. {
  60. $sjId = $merchant['id'];
  61. $orderId = $order['id'];
  62. $totalFee = 0;
  63. //根据流水类型定制通知内容
  64. switch ($capitalType) {
  65. //购买商品
  66. case dict::getDict('capitalType', 'xhOrder', 'id'):
  67. $totalFee = $order['actPrice'];
  68. $goodsList = xhOrderGoodsService::getAllByOrderId($orderId);
  69. if (!empty($goodsList)) {
  70. foreach ($goodsList as $goodsKey => $goodsVal) {
  71. $goodsId = $goodsVal['goodsId'];
  72. $goods = xhGoodsService::getById($goodsId);
  73. if (!empty($goods)) {
  74. $actualSold = stringUtil::calcAdd($goods['actualSold'], 1);
  75. xhGoodsService::updateById($goodsId, ['actualSold' => $actualSold]);//商品被售出数量+1
  76. }
  77. }
  78. }
  79. //收入提醒 ssh 2020.1.30
  80. $params = [
  81. 'order' => $order,
  82. ];
  83. $type = 'income';
  84. InformAdminService::addInform($shopId, $type, $params);
  85. break;
  86. default:
  87. }
  88. self::updateBySjId($sjId, $updateData);
  89. if ($isRecharge == false) {
  90. //数据统计,以下一定要排后面,否则数据不准确
  91. xhStatIncomeService::replace($sjId, $totalFee, $order['payWay']);
  92. xhStatIncomeMonthService::replace($sjId, $totalFee, $order['payWay']);
  93. StatIncomeSourceService::replaceData([
  94. 'sjId' => $order['sjId'],
  95. 'sourceType' => $order['sourceType'],
  96. 'amount' => $totalFee,
  97. 'payWay' => $order['payWay']
  98. ]);
  99. }
  100. }
  101. public static function add($data)
  102. {
  103. $return = xhMerchantAsset::add($data);
  104. return $return;
  105. }
  106. public static function withdraw()
  107. {
  108. $all = xhMerchantService::getAllByCondition(['status' => 1]);
  109. if (empty($all)) {
  110. return false;
  111. }
  112. foreach ($all as $merchant) {
  113. $connection = Yii::$app->db;
  114. $transaction = $connection->beginTransaction();
  115. try {
  116. $sjId = $merchant['id'];
  117. $merchantAsset = self::getBySjId($sjId);
  118. $amount = $merchantAsset['balance'];
  119. if ($amount <= 0) {
  120. Yii::info('余额不足');
  121. return false;
  122. }
  123. $mBalance = stringUtil::calcSub($merchantAsset['balance'], $amount);
  124. $newFreezeBalance = stringUtil::calcAdd($merchantAsset['freezeBalance'], $amount);
  125. $date = date("Y-m-d H:i:s");
  126. $id = stringUtil::generateMerchantCashOrderNo($sjId);
  127. $cashData = ['id' => $id, 'amount' => $amount, 'sjId' => $sjId, 'balance' => $mBalance, 'addTime' => time(), 'createTime' => $date];
  128. $order = xhDrawCashService::add($cashData);
  129. $orderId = $order['id'];
  130. xhMerchantAssetService::updateBySjId($sjId, ['balance' => $mBalance, 'freezeBalance' => $newFreezeBalance]);
  131. $now = time();
  132. $capitalTypeArray = dict::getDict('capitalType', 'xhDrawCash');
  133. $capitalType = $capitalTypeArray['id'];
  134. $mIncome = $merchantAsset['totalIncome'];
  135. $mExpend = $merchantAsset['totalExpend'];
  136. $payWay = dict::getDict('payWay', 'other');
  137. $capitalData = [
  138. 'relateId' => (string)$orderId,
  139. 'balance' => $mBalance,
  140. 'totalIncome' => $mIncome,
  141. 'totalExpend' => $mExpend,
  142. 'amount' => $amount,
  143. 'io' => 0,
  144. 'payWay' => $payWay,
  145. 'event' => '申请提现',
  146. 'sjId' => $sjId,
  147. 'userId' => 0,
  148. 'userName' => '',
  149. 'alipayId' => '',
  150. 'affectBalance' => 1,//会影响商家的余额
  151. 'createTime' => $date,
  152. 'addTime' => $now,
  153. 'capitalType' => $capitalType,
  154. 'operateId' => 0,
  155. ];
  156. xhSjCapitalService::add($capitalData);//商家资金流水记录增加
  157. // xhCommonService::sendMobileMsg('15280215347', '有客户申请提现,请及时处理');
  158. $id = $orderId;
  159. $draw = xhDrawCashService::getById($id);
  160. $drawAmount = isset($draw['amount']) ? floatval($draw['amount']) : 0;
  161. if ($draw['status'] == 1) {
  162. Yii::info('已经完成转账,请不要重复请求!');
  163. return;
  164. }
  165. $sjId = isset($draw['sjId']) ? $draw['sjId'] : 0;
  166. //$admin = xhAdminToMerchantService::getAdminByMerchantId($sjId);
  167. $time = strtotime(date("Y-m-d"));
  168. $income = xhStatIncomeService::getByIds($sjId, $time);
  169. $amount = isset($income['amount']) ? $income['amount'] : 0;
  170. $merchantExtInfo = xhMerchantExtendService::getBySjId($sjId);//取支付宝帐号
  171. $asset = xhMerchantAssetService::getBySjId($sjId);
  172. if ($merchantExtInfo['alipayAccount'] == '') {
  173. Yii::info('转账接收方的支付宝帐号为空');
  174. return;
  175. }
  176. if ($drawAmount == 0) {
  177. Yii::info('转账金额为0');
  178. return;
  179. }
  180. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  181. require_once($alipayWap . '/aop/AopClient.php');
  182. require_once($alipayWap . '/aop/request/AlipayFundTransToaccountTransferRequest.php');
  183. $extend = MerchantExtendService::getBySjId($sjId);
  184. $config = [
  185. //应用ID,您的APPID。
  186. 'app_id' => $extend['alipayPId'],
  187. //商户私钥,您的原始格式RSA私钥
  188. 'merchant_private_key' => $extend['alipayKey'],
  189. //异步通知地址
  190. 'notify_url' => Yii::$app->params['frontUrl'] . "/notice/ali-async",
  191. //同步跳转
  192. 'return_url' => "",
  193. //编码格式
  194. 'charset' => "UTF-8",
  195. //签名方式
  196. 'sign_type' => "RSA2",
  197. //支付宝网关
  198. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  199. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  200. 'alipay_public_key' => $extend['alipayPublicKey'],
  201. ];
  202. $aop = new \AopClient();
  203. $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  204. $aop->appId = $config['app_id'];
  205. $aop->rsaPrivateKey = $config['merchant_private_key'];
  206. $aop->alipayrsaPublicKey = $config['alipay_public_key'];
  207. $aop->apiVersion = '1.0';
  208. $aop->signType = 'RSA2';
  209. $aop->postCharset = 'UTF-8';
  210. $aop->format = 'json';
  211. $request = new \AlipayFundTransToaccountTransferRequest ();
  212. $request->setBizContent("{" .
  213. "\"out_biz_no\":\"" . $id . "\"," .
  214. "\"payee_type\":\"ALIPAY_LOGONID\"," .
  215. "\"payee_account\":\"" . $merchantExtInfo['alipayAccount'] . "\"," .
  216. "\"amount\":\"" . $drawAmount . "\"," .
  217. "\"payee_real_name\":\"" . $merchantExtInfo['alipayAccountName'] . "\"," .
  218. "\"payer_show_name\":\"厦门中花汇信息科技有限公司\"," .
  219. "\"remark\":\"提现申请\"" .
  220. " }");
  221. $result = $aop->execute($request);
  222. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  223. $resultCode = $result->$responseNode->code;
  224. $returnOrderId = $result->$responseNode->order_id;
  225. if (!empty($resultCode) && $resultCode == 10000) {
  226. xhDrawCashService::updateById($id, ['thirdSerialNumber' => $returnOrderId, 'status' => 1]);
  227. $remainAmount = stringUtil::calcSub($asset['freezeBalance'], $drawAmount);
  228. xhMerchantAssetService::updateBySjId($sjId, ['freezeBalance' => $remainAmount]);
  229. $transaction->commit();
  230. /*
  231. $openId = $admin['openId'];
  232. $openMerchant = xhWxOpenService::getMerchant();//取平台绑定的商家
  233. $openMerchantId = $openMerchant['id'];
  234. $allTM = xhTMessageService::getList($openMerchantId);
  235. $shortTempId = 'OPENTM201319876';
  236. if(isset($allTM[$shortTempId])){
  237. $tempId = $allTM[$shortTempId];
  238. $data = [
  239. "touser" => $openId,
  240. "template_id" => $tempId,
  241. "url" => Yii::$app->params['adminUrl'] . '/draw-cash/list',
  242. "data" => [
  243. "first" => ["value" => '已经完成结算。', "color" => "#173177"],
  244. "keyword1" => ["value" => '当天', "color" => "#173177"],
  245. "keyword2" => ["value" => $amount . '元', "color" => "#173177"],
  246. "remark" => ["value" => "支付宝收入:{$drawAmount}元,已汇入您的帐户。\n点击查看结算记录", "color" => "#173177"]
  247. ]
  248. ];
  249. }
  250. wxUtil::sendTaskInform($data, $openMerchant);
  251. */
  252. //xhCommonService::sendMobileMsg($admin['mobile'], "您的提现金额:{$drawAmount}元已经到帐,请注意查收。");
  253. } else {
  254. $msg = $result->$responseNode->msg;
  255. $sub_code = $result->$responseNode->sub_code;
  256. $sub_msg = $result->$responseNode->sub_msg;
  257. Yii::info("转帐失败,原因:code:" . $resultCode . " msg:" . $msg . " sub_code:" . $sub_code . " sub_msg:" . $sub_msg);
  258. $transaction->rollBack();
  259. }
  260. } catch (Exception $e) {
  261. $transaction->rollBack();
  262. }
  263. }
  264. }
  265. }