xhMerchantAssetService.php 11 KB

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