xhMerchantAssetService.php 11 KB

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