UserExtract.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: lianghuan
  5. * Date: 2018-03-03
  6. * Time: 16:47
  7. */
  8. namespace app\admin\model\user;
  9. use app\admin\model\wechat\WechatUser;
  10. use app\models\routine\RoutineTemplate;
  11. use think\facade\Route as Url;
  12. use crmeb\traits\ModelTrait;
  13. use crmeb\basic\BaseModel;
  14. use crmeb\services\WechatTemplateService;
  15. /**
  16. * 用户提现管理 model
  17. * Class User
  18. * @package app\admin\model\user
  19. */
  20. class UserExtract extends BaseModel
  21. {
  22. /**
  23. * 数据表主键
  24. * @var string
  25. */
  26. protected $pk = 'id';
  27. /**
  28. * 模型名称
  29. * @var string
  30. */
  31. protected $name = 'user_extract';
  32. use ModelTrait;
  33. /**
  34. * 获得用户提现总金额
  35. * @param $uid
  36. * @return mixed
  37. */
  38. public static function userExtractTotalPrice($uid, $status = 1, $where = [])
  39. {
  40. return self::getModelTime($where, self::where('uid', 'in', $uid)->where('status', $status))->sum('extract_price') ?: 0;
  41. }
  42. public static function extractStatistics()
  43. {
  44. //待提现金额
  45. $data['price'] = floatval(self::where('status', 0)->sum('extract_price'));
  46. //佣金总金额
  47. $data['brokerage_count'] = floatval(UserBill::getBrokerageCount());
  48. //已提现金额
  49. $data['priced'] = floatval(self::where('status', 1)->sum('extract_price'));
  50. //未提现金额
  51. $data['brokerage_not'] = bcsub(bcsub($data['brokerage_count'], $data['priced'], 2), $data['price'], 2);
  52. return compact('data');
  53. }
  54. /**
  55. * @param $where
  56. * @return array
  57. */
  58. public static function systemPage($where)
  59. {
  60. $model = new self;
  61. if ($where['date'] != '') {
  62. list($startTime, $endTime) = explode(' - ', $where['date']);
  63. $model = $model->where('a.add_time', '>', strtotime($startTime));
  64. $model = $model->where('a.add_time', '<', (int)bcadd(strtotime($endTime), 86400, 0));
  65. }
  66. if ($where['status'] != '') $model = $model->where('a.status', $where['status']);
  67. if ($where['extract_type'] != '') $model = $model->where('a.extract_type', $where['extract_type']);
  68. if ($where['nireid'] != '') $model = $model->where('a.real_name|a.id|b.nickname|a.bank_code|a.alipay_code', 'like', "%$where[nireid]%");
  69. $model = $model->alias('a');
  70. $model = $model->field('a.*,b.nickname');
  71. $model = $model->join('user b', 'b.uid=a.uid', 'LEFT');
  72. $model = $model->order('a.id desc');
  73. return self::page($model, $where);
  74. }
  75. public static function changeFail($id, $fail_msg)
  76. {
  77. $fail_time = time();
  78. $data = self::get($id);
  79. $extract_number = $data['extract_price'];
  80. $mark = '提现失败,退回佣金' . $extract_number . '元';
  81. $uid = $data['uid'];
  82. $status = -1;
  83. $User = User::where('uid', $uid)->find()->toArray();
  84. UserBill::income('提现失败', $uid, 'now_money', 'extract', $extract_number, $id, bcadd($User['now_money'], $extract_number, 2), $mark);
  85. User::bcInc($uid, 'brokerage_price', $extract_number, 'uid');
  86. $extract_type = '未知方式';
  87. switch ($data['extract_type']) {
  88. case 'alipay':
  89. $extract_type = '支付宝';
  90. break;
  91. case 'bank':
  92. $extract_type = '银行卡';
  93. break;
  94. case 'weixin':
  95. $extract_type = '微信';
  96. break;
  97. }
  98. if (strtolower($User['user_type']) == 'wechat') {
  99. WechatTemplateService::sendTemplate(WechatUser::where('uid', $uid)->value('openid'), WechatTemplateService::USER_BALANCE_CHANGE, [
  100. 'first' => $mark,
  101. 'keyword1' => '佣金提现',
  102. 'keyword2' => date('Y-m-d H:i:s', time()),
  103. 'keyword3' => $extract_number,
  104. 'remark' => '错误原因:' . $fail_msg
  105. ], Url::buildUrl('/user/cashrecord')->suffix('')->domain(true)->build());
  106. } else if (strtolower($User['user_type']) == 'routine') {
  107. RoutineTemplate::sendExtractFail($uid, $fail_msg, $extract_number, $User['nickname']);
  108. }
  109. return self::edit(compact('fail_time', 'fail_msg', 'status'), $id);
  110. }
  111. public static function changeSuccess($id)
  112. {
  113. $data = self::get($id);
  114. $extractNumber = $data['extract_price'];
  115. $mark = '成功提现佣金' . $extractNumber . '元';
  116. $wechatUserInfo = WechatUser::where('uid', $data['uid'])->field('openid,user_type,routine_openid,nickname')->find();
  117. $extract_type = '未知方式';
  118. switch ($data['extract_type']) {
  119. case 'alipay':
  120. $extract_type = '支付宝';
  121. break;
  122. case 'bank':
  123. $extract_type = '银行卡';
  124. break;
  125. case 'weixin':
  126. $extract_type = '微信';
  127. break;
  128. }
  129. if ($wechatUserInfo) {
  130. if (strtolower($wechatUserInfo->user_type) == 'routine') {
  131. $res = self::tixian('佣金提现', time().rand(1000,9999), $extractNumber, $wechatUserInfo['routine_openid']);
  132. if ($res['code'] == 'NO_AUTH') return false;
  133. RoutineTemplate::sendExtractSuccess($data['uid'], $extractNumber, $wechatUserInfo->nickname);
  134. } else if (strtolower($wechatUserInfo->user_type) == 'wechat') {
  135. WechatTemplateService::sendTemplate($wechatUserInfo->openid, WechatTemplateService::USER_BALANCE_CHANGE, [
  136. 'first' => $mark,
  137. 'keyword1' => '佣金提现',
  138. 'keyword2' => date('Y-m-d H:i:s', time()),
  139. 'keyword3' => $extractNumber,
  140. 'remark' => '点击查看我的佣金明细'
  141. ], Url::buildUrl('/user/cashrecord')->suffix('')->domain(true)->build());
  142. }
  143. }
  144. return self::edit(['status' => 1], $id);
  145. }
  146. /**
  147. * 测试方法
  148. *
  149. */
  150. public function test()
  151. {
  152. $batch_name = '余额提现';//转账的名称
  153. $out_trade_no = time().rand(1000,9999);//单号
  154. $money = 1;//金额
  155. $openid = 'o81tN5bU3rqOSq62i5FqcOP-LUy8';//用户openid
  156. $this->tixian($batch_name,$out_trade_no,1,$openid);
  157. }
  158. public static function tixian($batch_name,$out_trade_no,$money,$openid){
  159. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  160. $pars = [];
  161. $pars['appid'] = sys_config('pay_routine_appid');//直连商户的appid
  162. $pars['out_batch_no'] = 'sjzz'.date('Ymd').mt_rand(1000, 9999);//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
  163. $pars['batch_name'] = $batch_name;//该笔批量转账的名称
  164. $pars['batch_remark'] = $batch_name;//转账说明,UTF8编码,最多允许32个字符
  165. $pars['total_amount'] = intval($money * 100);//转账总金额 单位为“分”
  166. $pars['total_num'] = 1;//转账总笔数
  167. $pars['transfer_detail_list'][0] = [
  168. 'out_detail_no'=>'Dh'.$out_trade_no,
  169. 'transfer_amount'=>$pars['total_amount'],
  170. 'transfer_remark'=>$batch_name,
  171. 'openid'=>$openid
  172. ];//转账明细列表
  173. $token = self::getToken($pars);//获取token
  174. $res = self::https_request($url,json_encode($pars),$token);//发送请求
  175. $resArr = json_decode($res,true);
  176. return $resArr;
  177. //成功返回
  178. // array(3) {
  179. // ["batch_id"] => string(40) "1030001016101247194272022062900873000000"
  180. // ["create_time"] => string(25) "2022-06-29T10:21:30+08:00"
  181. // ["out_batch_no"] => string(16) "sjzz202206291647001"
  182. // }
  183. }
  184. public static function https_request($url,$data = null,$token){
  185. $curl = curl_init();
  186. curl_setopt($curl, CURLOPT_URL, (string)$url);
  187. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  188. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  189. if (!empty($data)){
  190. curl_setopt($curl, CURLOPT_POST, 1);
  191. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  192. }
  193. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  194. //添加请求头
  195. $headers = [
  196. 'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
  197. 'Accept: application/json',
  198. 'Content-Type: application/json; charset=utf-8',
  199. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  200. ];
  201. if(!empty($headers)){
  202. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  203. }
  204. $output = curl_exec($curl);
  205. curl_close($curl);
  206. return $output;
  207. }
  208. public static function getToken($pars)
  209. {
  210. // $url = 'https://api.mch.weixin.qq.com/v3/certificates';
  211. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  212. $http_method = 'POST';//请求方法(GET,POST,PUT)
  213. $timestamp = time();//请求时间戳
  214. $url_parts = parse_url($url);//获取请求的绝对URL
  215. $nonce = $timestamp.rand('10000','99999');//请求随机串
  216. $body = json_encode((object)$pars);//请求报文主体
  217. $stream_opts = [
  218. "ssl" => [
  219. "verify_peer"=>false,
  220. "verify_peer_name"=>false,
  221. ]
  222. ];
  223. $apiclient_cert_path = sys_config('site_url').sys_config('pay_routine_client_cert');
  224. $apiclient_key_path =sys_config('site_url').sys_config('pay_routine_client_key');
  225. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
  226. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  227. $mch_private_key = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥
  228. $merchant_id = sys_config('pay_routine_mchid');//商户id
  229. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  230. $message = $http_method."\n".
  231. $canonical_url."\n".
  232. $timestamp."\n".
  233. $nonce."\n".
  234. $body."\n";
  235. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  236. $sign = base64_encode($raw_sign);//签名
  237. $schema = 'WECHATPAY2-SHA256-RSA2048';
  238. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  239. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  240. return $token;
  241. }
  242. //获取头部提现信息
  243. public static function getExtractHead()
  244. {
  245. //本月提现人数
  246. $month = self::getModelTime(['data' => 'month'], self::where('status', 1))->group('uid')->count();
  247. //本月提现笔数
  248. $new_month = self::getModelTime(['data' => 'month'], self::where('status', 1))->distinct(true)->count();
  249. //上月提现人数
  250. $last_month = self::whereTime('add_time', 'last month')->where('status', 1)->group('uid')->distinct(true)->count();
  251. //上月提现笔数
  252. $last_count = self::whereTime('add_time', 'last month')->where('status', 1)->count();
  253. //本月提现金额
  254. $extract_price = self::getModelTime(['data' => 'month'], self::where('status', 1))->sum('extract_price');
  255. //上月提现金额
  256. $last_extract_price = self::whereTime('add_time', 'last month')->where('status', 1)->sum('extract_price');
  257. return [
  258. [
  259. 'name' => '总提现人数',
  260. 'field' => '个',
  261. 'count' => self::where('status', 1)->group('uid')->count(),
  262. 'content' => '',
  263. 'background_color' => 'layui-bg-blue',
  264. 'sum' => '',
  265. 'class' => 'fa fa-bar-chart',
  266. ],
  267. [
  268. 'name' => '总提现笔数',
  269. 'field' => '笔',
  270. 'count' => self::where('status', 1)->distinct(true)->count(),
  271. 'content' => '',
  272. 'background_color' => 'layui-bg-cyan',
  273. 'sum' => '',
  274. 'class' => 'fa fa-line-chart',
  275. ],
  276. [
  277. 'name' => '本月提现人数',
  278. 'field' => '人',
  279. 'count' => $month,
  280. 'content' => '',
  281. 'background_color' => 'layui-bg-orange',
  282. 'sum' => '',
  283. 'class' => 'fa fa-line-chart',
  284. ],
  285. [
  286. 'name' => '本月提现笔数',
  287. 'field' => '笔',
  288. 'count' => $new_month,
  289. 'content' => '',
  290. 'background_color' => 'layui-bg-green',
  291. 'sum' => '',
  292. 'class' => 'fa fa-line-chart',
  293. ],
  294. [
  295. 'name' => '本月提现金额',
  296. 'field' => '元',
  297. 'count' => $extract_price,
  298. 'content' => '提现总金额',
  299. 'background_color' => 'layui-bg-cyan',
  300. 'sum' => self::where('status', 1)->sum('extract_price'),
  301. 'class' => 'fa fa-line-chart',
  302. ],
  303. [
  304. 'name' => '上月提现人数',
  305. 'field' => '个',
  306. 'count' => $last_month,
  307. 'content' => '环比增幅',
  308. 'background_color' => 'layui-bg-blue',
  309. 'sum' => $last_month == 0 ? '100%' : bcdiv($month, $last_month, 2) * 100,
  310. 'class' => $last_month == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
  311. ],
  312. [
  313. 'name' => '上月提现笔数',
  314. 'field' => '笔',
  315. 'count' => $last_count,
  316. 'content' => '环比增幅',
  317. 'background_color' => 'layui-bg-black',
  318. 'sum' => $last_count == 0 ? '100%' : bcdiv($new_month, $last_count, 2) * 100,
  319. 'class' => $last_count == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
  320. ],
  321. [
  322. 'name' => '上月提现金额',
  323. 'field' => '元',
  324. 'count' => $last_extract_price,
  325. 'content' => '环比增幅',
  326. 'background_color' => 'layui-bg-gray',
  327. 'sum' => $last_extract_price == 0 ? '100%' : bcdiv($extract_price, $last_extract_price, 2) * 100,
  328. 'class' => $last_extract_price == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
  329. ],
  330. ];
  331. }
  332. //获取提现分布图和提现人数金额曲线图
  333. public static function getExtractList($where, $limit = 15)
  334. {
  335. $legdata = ['提现人数', '提现金额'];
  336. $list = self::getModelTime($where, self::where('status', 1))
  337. ->field('FROM_UNIXTIME(add_time,"%Y-%c-%d") as un_time,count(uid) as count,sum(extract_price) as sum_price')->group('un_time')->order('un_time asc')->select();
  338. if (count($list)) $list = $list->toArray();
  339. $xdata = [];
  340. $itemList = [0 => [], 1 => []];
  341. $chatrList = [];
  342. $zoom = '';
  343. foreach ($list as $value) {
  344. $xdata[] = $value['un_time'];
  345. $itemList[0][] = $value['count'];
  346. $itemList[1][] = $value['sum_price'];
  347. }
  348. foreach ($legdata as $key => $name) {
  349. $item['name'] = $name;
  350. $item['type'] = 'line';
  351. $item['data'] = $itemList[$key];
  352. $chatrList[] = $item;
  353. }
  354. unset($item, $name, $key);
  355. if (count($xdata) > $limit) $zoom = $xdata[$limit - 5];
  356. //饼状图
  357. $cake = ['支付宝', '银行卡', '微信'];
  358. $fenbulist = self::getModelTime($where, self::where('status', 1))
  359. ->field('count(uid) as count,extract_type')->group('extract_type')->order('count asc')->select();
  360. if (count($fenbulist)) $fenbulist = $fenbulist->toArray();
  361. $sum_count = self::getModelTime($where, self::where('status', 1))->count();
  362. $color = ['#FB7773', '#81BCFE', '#91F3FE'];
  363. $fenbudata = [];
  364. foreach ($fenbulist as $key => $item) {
  365. if ($item['extract_type'] == 'bank') {
  366. $item_date['name'] = '银行卡';
  367. } else if ($item['extract_type'] == 'alipay') {
  368. $item_date['name'] = '支付宝';
  369. } else if ($item['extract_type'] == 'weixin') {
  370. $item_date['name'] = '微信';
  371. }
  372. $item_date['value'] = bcdiv($item['count'], $sum_count, 2) * 100;
  373. $item_date['itemStyle']['color'] = $color[$key];
  374. $fenbudata[] = $item_date;
  375. }
  376. return compact('xdata', 'chatrList', 'legdata', 'zoom', 'cake', 'fenbudata');
  377. }
  378. /**
  379. * 获取用户累计提现金额
  380. * @param int $uid
  381. * @return int|mixed
  382. */
  383. public static function getUserCountPrice($uid = 0)
  384. {
  385. if (!$uid) return 0;
  386. $price = self::where('uid', $uid)->where('status', 1)->sum('extract_price');
  387. return $price ? $price : 0;
  388. }
  389. /**
  390. * 获取用户累计提现次数
  391. * @param int $uid
  392. * @return int|string
  393. */
  394. public static function getUserCountNum($uid = 0)
  395. {
  396. if (!$uid) return 0;
  397. return self::where('uid', $uid)->count();
  398. }
  399. }