xhMerchantAssetService.php 11 KB

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