UserExtractRepository.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author Qinii
  6. * @day 2020-06-16
  7. *
  8. *
  9. */
  10. namespace app\common\repositories\user;
  11. use alipay\aop\AlipayConfig;
  12. use alipay\aop\AopCertClient;
  13. use alipay\aop\request\AlipayFundTransUniTransferRequest;
  14. use app\common\repositories\BaseRepository;
  15. use app\common\dao\user\UserExtractDao as dao;
  16. use app\common\repositories\merchant\MerchantRepository;
  17. use crmeb\jobs\SendTemplateMessageJob;
  18. use crmeb\services\SwooleTaskService;
  19. use think\Exception;
  20. use think\facade\Db;
  21. use think\facade\App;
  22. use think\facade\Queue;
  23. class UserExtractRepository extends BaseRepository
  24. {
  25. /**
  26. * @var dao
  27. */
  28. protected $dao;
  29. protected $wxapp = array(
  30. 'app_id'=>'wxbf753066ac8686ba',
  31. 'applet_app_id'=>'wx9082e5ac2fdb513f',
  32. 'mchid'=>'1605734712',
  33. 'certPem'=>'/pkey/cert/apiclient_cert.pem',
  34. 'keyPem'=>'/pkey/cert/apiclient_key.pem'
  35. );
  36. /**
  37. * UserExtractRepository constructor.
  38. * @param dao $dao
  39. */
  40. public function __construct(dao $dao)
  41. {
  42. $this->dao = $dao;
  43. }
  44. /**
  45. * TODO
  46. * @param $id
  47. * @return bool
  48. * @author Qinii
  49. * @day 2020-06-16
  50. */
  51. public function getWhereCount($id)
  52. {
  53. $where['extract_id'] = $id;
  54. $where['status'] = 0;
  55. return $this->dao->getWhereCount($where) > 0;
  56. }
  57. /**
  58. * TODO
  59. * @param array $where
  60. * @param $page
  61. * @param $limit
  62. * @return array
  63. * @author Qinii
  64. * @day 2020-06-16
  65. */
  66. public function serach(array $where,$page,$limit)
  67. {
  68. if(isset($where['mer_id'])){
  69. $where['mer_id']=isset($where['mer_id'])?$where['mer_id']:"";
  70. }
  71. $mer_ids=[];
  72. if(isset($where['mer_name']) && $where['mer_name']!=''){
  73. $mer_ids=Db::name('merchant')->whereLike('mer_name','%'.$where['mer_name'].'%')->column('mer_id');
  74. }
  75. unset($where['mer_name']);
  76. $uids[]=0;
  77. $keyword='';
  78. if($where['keyword']!=''){
  79. $keyword=$where['keyword'];
  80. $uids=Db::name('user_certification')
  81. ->alias('uc')
  82. ->join('user_extract ue','uc.uid = ue.uid')
  83. ->join('user u','uc.uid = u.uid')
  84. ->whereLike('uc.user_name','%'.$where['keyword'].'%')
  85. ->whereOr('u.account','like','%'.$where['keyword'].'%')
  86. ->group('uc.uid')
  87. ->column('uc.uid');
  88. unset($where['keyword']);
  89. }
  90. $query = $this->dao->serach($where)
  91. ->when($keyword,function($query)use($keyword,$uids){
  92. $query->where(function($query)use($keyword,$uids){
  93. $query->where('real_name','like','%'.$keyword.'%')
  94. ->whereOr('bank_code','like','%'.$keyword.'%')
  95. ->whereOr('alipay_code','like','%'.$keyword.'%')
  96. ->whereOr('wechat','like','%'.$keyword.'%')
  97. ->whereOr('uid','in',$uids);
  98. });
  99. })
  100. ->when(($where['identity'] ?? '') == 'user', function ($query) {
  101. $query->where('mer_id is null');
  102. })
  103. ->when(($where['identity'] ?? '') == 'mer', function ($query) {
  104. $query->where('mer_id is not null');
  105. })
  106. ->when($mer_ids,function ($q) use ($mer_ids){$q->where('mer_id','in',$mer_ids);});
  107. $query_sql= clone $query;
  108. $count = $query->count();
  109. $list = $query->page($page,$limit)->order("extract_id desc")->select();
  110. if($list){
  111. foreach($list as $key => &$value){
  112. $value['real_name'] = $value['real_name'].'['.Db::name('user_certification') -> where('uid',$value['uid']) -> value('user_name').']';
  113. $value['phone'] =Db::name('user') -> where('uid',$value['uid']) -> value('phone');
  114. $value['mer_name'] ='平台';
  115. if($value['mer_id']){
  116. $value['mer_name'] = Db::name('merchant')->where('mer_id',$value['mer_id'])->value('mer_name');
  117. }
  118. }
  119. }
  120. if(isset($where['mer_id']) && $where['mer_id']!=''){
  121. $where2['mer_id']=isset($where['mer_id'])?$where['mer_id']:'';
  122. $mer_id = $where['mer_id'];
  123. $bill_number = Db::name("user_bill")->where('mer_id', $mer_id)->where('status', 1)->whereIn('commission_type', [7, 17, 19])->sum('number');
  124. $uids2=$query_sql->group('uid')->column('uid');
  125. //总额
  126. $zonge_1=$bill_number;
  127. $zonge_2=sprintf("%.2f", $bill_number * 0.06);
  128. //已提现
  129. $tixian_1=Db::name("user_extract") ->where($where2)->where('status',1)->whereIn('uid',$uids2)->sum("extract_price");
  130. $tixian_2=Db::name("user_extract") ->where($where2)->where('status',1)->whereIn('uid',$uids2)->sum("service_money");
  131. //审核中
  132. $shenhezhong_1=Db::name("user_extract") ->where($where2)->where('status',0)->whereIn('uid',$uids2)->sum("extract_price");
  133. $shenhezhong_2=Db::name("user_extract") ->where($where2)->where('status',0)->whereIn('uid',$uids2)->sum("service_money");
  134. //增加【实际提现】模块,实际提现金额=已提现金额*(1-综合服务费率)
  135. $countmoyer=[
  136. //总额
  137. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_1, 'field'=>'元', 'name'=> '收益总额' ],
  138. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_2, 'field'=>'元', 'name'=> '综合服务费总额' ],
  139. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($zonge_1-$zonge_2)), 'field'=>'元', 'name'=> '实际到账总额' ],
  140. //已提现
  141. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_1, 'field'=>'元', 'name'=> '已提现总额' ],
  142. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_2, 'field'=>'元', 'name'=> '综合服务费' ],
  143. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($tixian_1-$tixian_2)), 'field'=>'元', 'name'=> '实际到账总额' ],
  144. //审核中
  145. ['className'=> 'el-icon-s-goods', 'count'=>$shenhezhong_1, 'field'=>'元', 'name'=> '审核中总额' ],
  146. ['className'=> 'el-icon-s-goods', 'count'=>$shenhezhong_2, 'field'=>'元', 'name'=> '综合服务费' ],
  147. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($shenhezhong_1-$shenhezhong_2)), 'field'=>'元', 'name'=> '实际到账总额' ]
  148. ];
  149. }else{
  150. if (($where['identity'] ?? '') == 'user') {
  151. $bill_number = Db::name("user_bill")->where('status', 1)->whereNotIn('commission_type', [5, 7, 17, 19])->sum('number');
  152. }
  153. if (($where['identity'] ?? '') == 'mer') {
  154. $bill_number = Db::name("user_bill")->where('status', 1)->whereIn('commission_type', [7, 17, 19])->sum('number');
  155. }
  156. $zonge_1=$bill_number;
  157. $tixian_1=Db::name("user_extract")->when(($where['identity'] ?? '') == 'user', function ($query) {
  158. $query->where('mer_id is null');
  159. })
  160. ->when(($where['identity'] ?? '') == 'mer', function ($query) {
  161. $query->where('mer_id is not null');
  162. })->where('status',1)->sum("extract_price");
  163. $tixian_2=Db::name("user_extract")->when(($where['identity'] ?? '') == 'user', function ($query) {
  164. $query->where('mer_id is null');
  165. })
  166. ->when(($where['identity'] ?? '') == 'mer', function ($query) {
  167. $query->where('mer_id is not null');
  168. })->where('status',1)->sum("service_money");
  169. $shenhezhong_1=Db::name("user_extract")->when(($where['identity'] ?? '') == 'user', function ($query) {
  170. $query->where('mer_id is null');
  171. })
  172. ->when(($where['identity'] ?? '') == 'mer', function ($query) {
  173. $query->where('mer_id is not null');
  174. })->where('status',0)->sum("extract_price");
  175. $count1 = $query->where("status",1)->sum("extract_price");
  176. $count2 = Db::name("user")->sum("brokerage_price");
  177. if (($where['identity'] ?? '') == 'mer') {
  178. $count2 = Db::name("merchant")->sum("brokerage_price");
  179. }
  180. $countmoyer=[
  181. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_1, 'field'=>'元', 'name'=> '奖励总额' ],
  182. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_1, 'field'=>'元', 'name'=> '已提现' ],
  183. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_1 - $tixian_2, 'field'=>'元', 'name'=> '实际提现' ],
  184. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_1 - $tixian_1 - $shenhezhong_1, 'field'=>'元', 'name'=> '未提现' ],
  185. ['className'=> 'el-icon-s-goods', 'count'=>$shenhezhong_1, 'field'=>'元', 'name'=> '审核中' ],
  186. ];
  187. }
  188. return compact('count','list',"countmoyer");
  189. }
  190. /**
  191. * TODO
  192. * @param array $where
  193. * @param $page
  194. * @param $limit
  195. * @return array
  196. * @author Qinii
  197. * @day 2020-06-16
  198. */
  199. public function new_search(array $where,$page,$limit)
  200. {
  201. if(isset($where['mer_id'])){
  202. $where['mer_id']=isset($where['mer_id'])?$where['mer_id']:"";
  203. }
  204. $mer_ids=[];
  205. if(isset($where['mer_name']) && $where['mer_name']!=''){
  206. $mer_ids=Db::name('merchant')->whereLike('mer_name','%'.$where['mer_name'].'%')->column('mer_id');
  207. }
  208. unset($where['mer_name']);
  209. $uids[]=0;
  210. $keyword='';
  211. if($where['keyword']!=''){
  212. $keyword=$where['keyword'];
  213. $uids=Db::name('user_certification')
  214. ->alias('uc')
  215. ->join('user_extract ue','uc.uid = ue.uid')
  216. ->join('user u','uc.uid = u.uid')
  217. ->whereLike('uc.user_name','%'.$where['keyword'].'%')
  218. ->whereOr('u.account','like','%'.$where['keyword'].'%')
  219. ->group('uc.uid')
  220. ->column('uc.uid');
  221. unset($where['keyword']);
  222. }
  223. $query = $this->dao->serach($where)
  224. ->when($keyword,function($query)use($keyword,$uids){
  225. $query->where(function($query)use($keyword,$uids){
  226. $query->where('real_name','like','%'.$keyword.'%')
  227. ->whereOr('bank_code','like','%'.$keyword.'%')
  228. ->whereOr('alipay_code','like','%'.$keyword.'%')
  229. ->whereOr('wechat','like','%'.$keyword.'%')
  230. ->whereOr('uid','in',$uids);
  231. });
  232. })
  233. // ->when($where['identity'] == 'user', function ($query) {
  234. // $query->where('mer_id is null');
  235. // })
  236. // ->when($where['identity'] == 'mer', function ($query) {
  237. // $query->where('mer_id is not null');
  238. // })
  239. ->when($mer_ids,function ($q) use ($mer_ids){$q->where('mer_id','in',$mer_ids);});
  240. $query_sql= clone $query;
  241. $count = $query->count();
  242. $list = $query->page($page,$limit)->order("extract_id desc")->select();
  243. if($list){
  244. foreach($list as $key => &$value){
  245. $value['real_name'] = $value['real_name'].'['.Db::name('user_certification') -> where('uid',$value['uid']) -> value('user_name').']';
  246. $value['phone'] =Db::name('user') -> where('uid',$value['uid']) -> value('phone');
  247. $value['mer_name'] ='平台';
  248. if($value['mer_id']){
  249. $value['mer_name'] = Db::name('merchant')->where('mer_id',$value['mer_id'])->value('mer_name');
  250. }
  251. }
  252. }
  253. $where2['mer_id']=isset($where['mer_id'])?$where['mer_id']:'';
  254. $uids2=$query_sql->group('uid')->column('uid');
  255. //总额
  256. $zonge_1=Db::name("user_extract")->whereIn('uid',$uids2)->sum("extract_price");
  257. $zonge_2=Db::name("user_extract")->whereIn('uid',$uids2)->sum("service_money");
  258. //已提现
  259. $tixian_1=Db::name("user_extract")->where('status',1)->whereIn('uid',$uids2)->sum("extract_price");
  260. $tixian_2=Db::name("user_extract")->where('status',1)->whereIn('uid',$uids2)->sum("service_money");
  261. //审核中
  262. $shenhezhong_1=Db::name("user_extract")->where('status',0)->whereIn('uid',$uids2)->sum("extract_price");
  263. $shenhezhong_2=Db::name("user_extract")->where('status',0)->whereIn('uid',$uids2)->sum("service_money");
  264. //增加【实际提现】模块,实际提现金额=已提现金额*(1-综合服务费率)
  265. $countmoyer=[
  266. //总额
  267. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_1, 'field'=>'元', 'name'=> '收益总额' ],
  268. ['className'=> 'el-icon-s-goods', 'count'=>$zonge_2, 'field'=>'元', 'name'=> '综合服务费总额' ],
  269. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($zonge_1-$zonge_2)), 'field'=>'元', 'name'=> '实际到账总额' ],
  270. //已提现
  271. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_1, 'field'=>'元', 'name'=> '已提现总额' ],
  272. ['className'=> 'el-icon-s-goods', 'count'=>$tixian_2, 'field'=>'元', 'name'=> '综合服务费' ],
  273. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($tixian_1-$tixian_2)), 'field'=>'元', 'name'=> '实际到账总额' ],
  274. //审核中
  275. ['className'=> 'el-icon-s-goods', 'count'=>$shenhezhong_1, 'field'=>'元', 'name'=> '审核中总额' ],
  276. ['className'=> 'el-icon-s-goods', 'count'=>$shenhezhong_2, 'field'=>'元', 'name'=> '综合服务费' ],
  277. ['className'=> 'el-icon-s-goods', 'count'=>set_price_rtrim(decimal2($shenhezhong_1-$shenhezhong_2)), 'field'=>'元', 'name'=> '实际到账总额' ]
  278. ];
  279. return compact('count','list',"countmoyer");
  280. }
  281. public function get_user_extract_item($extract_id)
  282. {
  283. return Db::name('user_extract_item')->where('extract_id',$extract_id)->select();
  284. }
  285. /**
  286. * @param $uid
  287. * @return mixed
  288. * @author xaboy
  289. * @day 2020/6/22
  290. */
  291. public function userTotalExtract($uid)
  292. {
  293. return $this->dao->serach(['status' => 1, 'uid' => $uid])->sum('extract_price');
  294. }
  295. /**
  296. * TODO
  297. * @param $user
  298. * @param $data
  299. * @author Qinii
  300. * @day 2020-06-16
  301. */
  302. public function create($user,$data,$uid,$type=1)
  303. {
  304. $userData = Db::name('user') -> where('uid',$uid) -> find();
  305. if ($data["extract_type"]==1){
  306. $data["wechat"]=$userData['account'];
  307. $data["extract_pic"]='';
  308. $data["real_name"]=$userData['nickname'];
  309. $data['order_sn'] = 'wx'.time().rand(100000, 999999);
  310. }else if($data["extract_type"]==2) {
  311. if ($userData['ali_user_id'] == '0' || $userData['ali_user_id'] == '') {
  312. return false;
  313. }
  314. $data["alipay_code"] = $userData["account"];
  315. $data["real_name"] = $userData["nickname"];
  316. $data['order_sn'] = 'al' . time() . rand(100000, 999999);
  317. }else if($data["extract_type"]==3){
  318. $account_info=Db::name("user_withdraw_account")->where(["id"=>$data["bank_id"],"account_type"=>$data["extract_type"],"user_id"=>$uid])->find();
  319. if(!$account_info){
  320. return false;
  321. }
  322. $data["bank_code"]=$account_info["account"];
  323. $data["real_name"]=$account_info['info'];
  324. $data["bank_address"]=$account_info['bank_name'];
  325. $data['order_sn'] = 'tx'.time().rand(100000, 999999);
  326. $data["bank_info"]= json_encode($account_info, true);
  327. unset($data['bank_id']);
  328. }else{
  329. return false;
  330. }
  331. if ($data["extract_type"]==3){
  332. $data = Db::transaction(function()use($user,$data, $type,$uid){
  333. if($type==1){
  334. $brokerage_price = bcsub($user['brokerage_price'],$data['extract_price'],2);
  335. $user->brokerage_price = $brokerage_price;
  336. }else if ($type == 2) {
  337. $brokerage_price = bcsub($user['member_brokerage_price'],$data['extract_price'],2);
  338. $user->member_brokerage_price = $brokerage_price;
  339. }else if ($type == 3) {
  340. $hongbao = bcsub($user['hongbao'],$data['extract_price'],2);
  341. $user->hongbao = $hongbao;
  342. }
  343. $user->save();
  344. $service_money=bcmul($data['extract_price'],'0.1',2);
  345. $data['service_money']=$service_money;
  346. $data['status'] = 0;
  347. $data['uid'] = $user['uid'];
  348. $data['type']=$type;
  349. $data['withdrawal_type'] =3;
  350. return $this->dao->create($data);
  351. });
  352. }else{
  353. $data = Db::transaction(function()use($user,$data,$uid,$type){
  354. if($type==1){
  355. $brokerage_price = bcsub($user['brokerage_price'],$data['extract_price'],2);
  356. $user->brokerage_price = $brokerage_price;
  357. }else if ($type == 2) {
  358. $brokerage_price = bcsub($user['member_brokerage_price'],$data['extract_price'],2);
  359. $user->member_brokerage_price = $brokerage_price;
  360. }else if ($type == 3) {
  361. $hongbao = bcsub($user['hongbao'],$data['extract_price'],2);
  362. $user->hongbao = $hongbao;
  363. }
  364. $user->save();
  365. $service_money=bcmul($data['extract_price'],'0.1',2);
  366. $data['service_money']=$service_money;
  367. $data['status'] = 0;
  368. $data['uid'] = $user['uid'];
  369. $data['types'] = $type;
  370. $data['statbalanceus'] = $brokerage_price;
  371. $extract=$this->dao->create($data);
  372. $tea_price=Db::name('user_rich')->where('uid', $uid)->value('tea_price');
  373. $extract_price_yihu=0;
  374. $service_money_yihu=0;
  375. if($tea_price && $tea_price>0){
  376. if($tea_price>=$data['extract_price']){
  377. $extract_price_yihu= $data['extract_price'];
  378. $service_money_yihu= $data['service_money'];
  379. }else{
  380. $extract_price_yihu= $tea_price;
  381. $service_money_yihu= bcmul($tea_price,'0.1',2);
  382. }
  383. }
  384. if($type == 3){
  385. //加入红包提现记录
  386. $insertdata = [
  387. 'uid'=> $uid,
  388. 'number' => $data['extract_price'],
  389. 'surplus' => $user->hongbao,
  390. 'mark' => '红包提现',
  391. 'type' => 2,
  392. 'status' => -1,
  393. 'addtime' => time(),
  394. ];
  395. Db::name('user_sign_hongbao')->insertGetId($insertdata);
  396. }
  397. // if($extract_price_yihu>0){
  398. $insertAll[]=array(
  399. 'extract_id'=>$extract->extract_id,
  400. 'uid'=> $data['uid'],
  401. 'extract_type'=> $data["extract_type"],
  402. 'extract_price'=> $extract_price_yihu,
  403. 'service_money'=> $service_money_yihu,
  404. 'order_sn'=> $data['order_sn'],
  405. 'type'=> 1,//0- 幸福宝 1-一壶茶
  406. );
  407. // }
  408. $insertAll[]=array(
  409. 'extract_id'=>$extract->extract_id,
  410. 'uid'=> $data['uid'],
  411. 'extract_type'=> $data["extract_type"],
  412. 'extract_price'=> ($data['extract_price']-$extract_price_yihu),
  413. 'service_money'=> ($data['service_money']-$service_money_yihu),
  414. 'order_sn'=> $data['order_sn'],
  415. 'type'=> 0,//0- 幸福宝 1-一壶茶
  416. );
  417. DB::name('user_extract_item')->insertAll($insertAll);
  418. return $extract;
  419. });
  420. }
  421. SwooleTaskService::admin('notice', [
  422. 'type' => 'extract',
  423. 'title' => '您有一条新的提醒申请',
  424. 'id' => $data->extract_id
  425. ]);
  426. return true;
  427. }
  428. public function create_yhc($user, $merchant, $data)
  429. {
  430. Db::name("merchant")->where("mer_id", $merchant['mer_id'])->dec('brokerage_price', $data['extract_price'])->update();
  431. $data["bank_code"]=$merchant["bank_account"];
  432. $data["bank_address"]=$merchant["bank_deposit"];
  433. $data['order_sn'] = 'tx'.time().rand(100000, 999999);
  434. $data["real_name"]=$user['nickname'];
  435. $data['status'] = 0;
  436. $data['uid'] = $user['uid'];
  437. $data['types'] = 1;
  438. $data['type'] = 1;
  439. $data['mer_id'] = $merchant['mer_id'];
  440. $data['withdrawal_type'] =3;
  441. return $this->dao->create($data);
  442. }
  443. public function switchStatus($id,$data)
  444. {
  445. Db::transaction(function()use($id,$data){
  446. $extract = $this->dao->getWhere(['extract_id' => $id]);
  447. $user = app()->make(UserRepository::class)->get($extract['uid']);
  448. if($data['status'] == '-1'){
  449. if (!empty($extract['mer_id'])) {
  450. //商户提现逻辑处理
  451. $mer = app()->make(MerchantRepository::class)->get($extract['mer_id']);
  452. $brokerage_price = bcadd($mer['brokerage_price'] ,$extract['extract_price'],2);
  453. $mer->brokerage_price = $brokerage_price;
  454. $mer->save();
  455. } else {
  456. //用户提现逻辑处理
  457. if($extract['types']==1){
  458. $brokerage_price = bcadd($user['brokerage_price'] ,$extract['extract_price'],2);
  459. //返回余额
  460. $user->brokerage_price = $brokerage_price;
  461. }else if($extract['types']==3){
  462. $user->hongbao = bcadd($user->hongbao,$extract['extract_price'],2);
  463. }else{
  464. $member_brokerage_price = bcadd($user['member_brokerage_price'] ,$extract['extract_price'],2);
  465. //返回余额
  466. $user->member_brokerage_price = $member_brokerage_price;
  467. Db::name('user_rich')->where('uid',$extract['uid'])->inc('red', $extract['extract_price'])->update();
  468. Db::name('user_rich_log')->insert([
  469. 'uid' => $extract['uid'],
  470. 'red' => $extract['extract_price'],
  471. 'pm' => 1,
  472. 'time' => time(),
  473. 'order_id' => 0,
  474. 'mark' => '提现失败返还红积分'
  475. ]);
  476. }
  477. $user->save();
  478. }
  479. // //返回积分
  480. // $user->score = bcadd($user['score'] ,$extract['extract_price'],2);
  481. // $user->save();
  482. // Db::name('user_sign_score')->where("order_type","extract") -> where("order_id",$id) -> update(['status'=>0]);
  483. }else{
  484. if($extract['types']==3){
  485. //加入红包出账记录
  486. $insertdata = [
  487. 'uid'=> $user->uid,
  488. 'number' => $extract['extract_price'],
  489. 'surplus' => $user->hongbao,
  490. 'mark' => '红包提现',
  491. 'type' => 2,
  492. 'status' => 1,
  493. 'addtime' => time(),
  494. ];
  495. Db::name('user_sign_hongbao')->insertGetId($insertdata);
  496. }
  497. //积分扣除
  498. // Db::name('user_sign_score')->where("order_type","extract") -> where("order_id",$id) -> update(['status'=>1]);
  499. }
  500. $this->dao->update($id,$data);
  501. });
  502. Queue::push(SendTemplateMessageJob::class,[
  503. 'tempCode' => 'ORDER_DELIVER_SUCCESS',
  504. 'id' =>$id
  505. ]);
  506. }
  507. /**
  508. * @remarks 微信商家转账到零钱
  509. * @author Tang
  510. * @created 2023/10/31
  511. */
  512. public function WechatTransfers($id)
  513. {
  514. $userdata=Db::name('user_extract')
  515. ->alias('u_e')
  516. ->leftJoin('user_extract_openid u_e_o','u_e.uid=u_e_o.uid')
  517. ->where(['extract_id' => $id,'extract_type'=>1])
  518. ->field('u_e.extract_price,u_e.uid,u_e_o.openid,u_e_o.type as u_e_o_type,u_e.service_money,u_e.withdrawal_type,u_e.order_sn,u_e.mer_id')
  519. ->find();
  520. if($userdata and !empty($userdata)){
  521. if($userdata['withdrawal_type']==2){
  522. $money= bcsub($userdata['extract_price'],$userdata['service_money'],2);
  523. }else{
  524. $money= bcsub($userdata['extract_price'],$userdata['service_money'],2);
  525. }
  526. // $money=$userdata['extract_price'];//测试不加手续手续费
  527. $res=$this->transfer('提现到微信零钱', $userdata['order_sn'], $money, $userdata['openid'],$userdata['u_e_o_type']);
  528. if(isset($res['code']) && isset($res['message'])) {
  529. return ['code'=>500,'msg'=>$res['message']];
  530. }else{
  531. Db::name('user_extract')->where('extract_id',$id)->update(['wx_status'=>1]);
  532. return ['code'=>201,'msg'=>'微信正在处理'];
  533. }
  534. // else if($res['batch_status']=='ACCEPTED' || $res['batch_status']=='PROCESSING'){
  535. // Db::name('user_extract')->where('extract_id',$id)->update(['wx_status'=>1]);
  536. // return ['code'=>201,'msg'=>'微信正在处理'];
  537. // }else if($res['batch_status']=='FINISHED'){
  538. // //FINISHED:已完成。批次内的所有转账明细单都已处理完成
  539. // Db::name('entropy_barter_bill')->where('order_no', $userdata['order_sn'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  540. // Db::name('user_extract')->where('extract_id',$id)->update(['status'=>1]);
  541. // return ['code'=>200,'msg'=>'审核成功'];
  542. // }
  543. // return ['code'=>500,'msg'=>'提现错误'];
  544. }else{
  545. return ['code'=>200,'msg'=>'未找到数据'];
  546. }
  547. }
  548. /**
  549. * 定时任务3分钟查询一次审核中的微信待处理的订单
  550. * @return array|bool
  551. * @throws \think\db\exception\DataNotFoundException
  552. * @throws \think\db\exception\DbException
  553. * @throws \think\db\exception\ModelNotFoundException
  554. */
  555. public function wechat_extract(){
  556. $user_extract_data=Db::name('user_extract')->where('wx_status',1)->where('status',0)->select();
  557. foreach ($user_extract_data as $v){
  558. $data=$this->batch_id($v['order_sn']);
  559. Db::name('log')->insert(['data'=>'微信审核------'.json_encode($data)]);
  560. if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='FINISHED' && $data['transfer_batch']['success_num']==1){
  561. Db::name('entropy_barter_bill')->where('order_no', $v['order_sn'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  562. Db::name('user_extract')->where('extract_id',$v['extract_id'])->update(['status'=>1]);
  563. }else if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='FINISHED' && $data['transfer_batch']['success_num']<1){
  564. $fail_msg='微信二次审核已驳回';
  565. Db::name('user_extract')->where('order_sn',$v['order_sn'])->update(['fail_msg'=>$fail_msg,'status_time'=>date('Y-m-d H:i:s'),'status'=>'-1']);
  566. if($v['withdrawal_type']==1){
  567. Db::name('user')->where('uid',$v['uid'])->inc('brokerage_price',$v['extract_price'])->update();
  568. }else{
  569. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$v['order_sn'])->where('pm',2)->find();
  570. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$fail_msg]);
  571. Db::name('entropy_barter_user_'.$v['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$v['extract_price'])->update();
  572. }
  573. }else if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='CLOSED'){
  574. $fail_msg=(isset($data['transfer_batch']['close_reason']) && $data['transfer_batch']['close_reason']!='')?$data['transfer_batch']['close_reason']:'系统超时未审核,已取消';
  575. Db::name('user_extract')->where('order_sn',$v['order_sn'])->update(['fail_msg'=>$fail_msg,'status_time'=>date('Y-m-d H:i:s'),'status'=>'-1']);
  576. if($v['withdrawal_type']==1){
  577. Db::name('user')->where('uid',$v['uid'])->inc('brokerage_price',$v['extract_price'])->update();
  578. }else{
  579. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$v['order_sn'])->where('pm',2)->find();
  580. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$fail_msg]);
  581. Db::name('entropy_barter_user_'.$v['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$v['extract_price'])->update();
  582. }
  583. }
  584. }
  585. return true;
  586. }
  587. /**
  588. * 商家转账到零钱(公众号:程序员在囧途)
  589. * @param $batch_name
  590. * @param $out_trade_no
  591. * @param $money
  592. * @param $openid
  593. */
  594. private function transfer($batch_name, $out_trade_no, $money, $openid,$type=0)
  595. {
  596. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  597. $pars = [];
  598. if($type==1){
  599. $pars['appid'] = $this->wxapp['applet_app_id'];//直连商户的appid 小程序的
  600. }else{
  601. $pars['appid'] = $this->wxapp['app_id'];//直连商户的appid APP的
  602. }
  603. $pars['out_batch_no'] = $out_trade_no;//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
  604. $pars['batch_name'] = $batch_name;//该笔批量转账的名称
  605. $pars['batch_remark'] = $batch_name;//转账说明,UTF8编码,最多允许32个字符
  606. $pars['total_amount'] = intval($money * 100);//转账总金额 单位为“分”
  607. $pars['total_num'] = 1;//转账总笔数
  608. $pars['transfer_detail_list'][0] = [
  609. 'out_detail_no' => 'transfer' . $out_trade_no,
  610. 'transfer_amount' => $pars['total_amount'],
  611. 'transfer_remark' => $batch_name,
  612. 'openid' => $openid
  613. ];//转账明细列表
  614. $token = $this->getToken($url,$pars);//获取token
  615. $res = $this->https_request($url, json_encode($pars), $token);//发送请求
  616. return json_decode($res, true);
  617. }
  618. /**
  619. * 通过商家批次单号查询批次单
  620. * @param $order_sn
  621. * @return mixed
  622. *
  623. * 【批次状态】 ACCEPTED:已受理。批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认
  624. * PROCESSING:转账中。已开始处理批次内的转账明细单
  625. * FINISHED:已完成。批次内的所有转账明细单都已处理完成
  626. * CLOSED:已关闭。可查询具体的批次关闭原因确认
  627. */
  628. private function batch_id($order_sn)
  629. {
  630. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$order_sn.'?need_query_detail=false';
  631. $token = $this->getToken($url,null,'GET');//获取token
  632. $res = $this->https_request($url, null, $token);//发送请求
  633. return json_decode($res, true);
  634. }
  635. private function https_request($url, $data = null, $token)
  636. {
  637. $curl = curl_init();
  638. curl_setopt($curl, CURLOPT_URL, (string)$url);
  639. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  640. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  641. if (!empty($data)) {
  642. curl_setopt($curl, CURLOPT_POST, 1);
  643. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  644. }
  645. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  646. //添加请求头
  647. $headers = [
  648. 'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token,
  649. 'Accept: application/json',
  650. 'Content-Type: application/json; charset=utf-8',
  651. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  652. ];
  653. if (!empty($headers)) {
  654. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  655. }
  656. $output = curl_exec($curl);
  657. curl_close($curl);
  658. return $output;
  659. }
  660. private function getToken($url,$pars,$http_method='POST')
  661. {
  662. // $http_method = $http_method;//请求方法(GET,POST,PUT)
  663. $timestamp = time();//请求时间戳
  664. $url_parts = parse_url($url);//获取请求的绝对URL
  665. $nonce = $timestamp . rand('10000', '99999');//请求随机串
  666. if($pars){
  667. $body = json_encode((object)$pars);//请求报文主体
  668. }else{
  669. $body = '';
  670. }
  671. $stream_opts = [
  672. "ssl" => [
  673. "verify_peer" => false,
  674. "verify_peer_name" => false,
  675. ]
  676. ];
  677. // try {
  678. $filePath = App::getRootPath();
  679. $certPem= [
  680. 'certPem' => $filePath . $this->wxapp['certPem'],
  681. 'keyPem' => $filePath . $this->wxapp['keyPem'],
  682. ];
  683. $apiclient_cert_path = $certPem['certPem'];
  684. $apiclient_key_path = $certPem['keyPem'];
  685. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path, false, stream_context_create($stream_opts)));
  686. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  687. $mch_private_key = file_get_contents($apiclient_key_path, false, stream_context_create($stream_opts));//密钥
  688. $merchant_id = $this->wxapp['mchid'];
  689. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  690. $message = $http_method . "\n" .
  691. $canonical_url . "\n" .
  692. $timestamp . "\n" .
  693. $nonce . "\n" .
  694. $body . "\n";
  695. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  696. $sign = base64_encode($raw_sign);//签名
  697. // $schema = 'WECHATPAY2-SHA256-RSA2048';
  698. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  699. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  700. // } catch (\Exception $e) {
  701. // throw new \Exception(['msg' => $e->getMessage()]);
  702. // }
  703. return $token;
  704. }
  705. /**
  706. * 企业付款到零钱
  707. * @param $id
  708. * @return array
  709. * @throws \think\db\exception\DataNotFoundException
  710. * @throws \think\db\exception\DbException
  711. * @throws \think\db\exception\ModelNotFoundException
  712. */
  713. public function WechatTransfers_qiye($id)
  714. {
  715. // $extract = $this->dao->getWhere(['extract_id' => $id]);
  716. $userdata=Db::name('user_extract')
  717. ->alias('u_e')
  718. ->leftJoin('user_extract_openid u_e_o','u_e.uid=u_e_o.uid')
  719. ->where(['extract_id' => $id,'extract_type'=>1])
  720. ->field('u_e.extract_price,u_e.uid,u_e_o.openid,u_e.service_money,u_e.withdrawal_type,u_e.order_sn')
  721. ->find();
  722. if($userdata and !empty($userdata)){
  723. $params["mch_appid"]='wxbf753066ac8686ba';
  724. $params["mchid"] = '1605734712';
  725. $params["nonce_str"]= mt_rand(100000000,999999999);
  726. $params["partner_trade_no"] = $userdata['order_sn'];
  727. if($userdata['withdrawal_type']==2){
  728. $params["amount"]= bcmul(bcsub($userdata['extract_price'],$userdata['service_money'],2),100);
  729. }else{
  730. $params["amount"]= bcmul(bcsub($userdata['extract_price'],$userdata['service_money'],2),100);
  731. }
  732. $params["desc"]= '提现到微信零钱';
  733. $params["openid"]= $userdata['openid'];
  734. $params["check_name"]= 'NO_CHECK';
  735. $sign =$this->getSign($params);
  736. //生成签名
  737. $params['sign'] = $sign;
  738. //构造XML数据
  739. $xmldata = $this->ToXml($params); //数组转XML
  740. $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  741. //发送post请求
  742. $res = $this->curl_post_ssl($url, $xmldata,[]);
  743. // Db::name('log')->insert(['data'=>json_encode($res)]);
  744. if(!$res){
  745. return ['code'=>500,'msg'=>'请求未能发送成功'];
  746. }
  747. //付款结果分析
  748. $content = $this->FromXml($res); //xml转数组
  749. Db::name('log')->insert(['data'=>'【微信提现返回】'.json_encode($content)]);
  750. if($content['result_code']=="SUCCESS"){
  751. $this->WechatTransfers_query($userdata['order_sn']);
  752. return ['code'=>200,'msg'=>'成功'];
  753. }else{
  754. // Db::name('log')->insert(['data'=>'else进来了']);
  755. Db::name('user_extract')->where('order_sn',$userdata['order_sn'])->update(['fail_msg'=>$content['err_code_des'],'status_time'=>date('Y-m-d H:i:s'),'status'=>'-1']);
  756. $extract_data=Db::name('user_extract')->where('order_sn',$userdata['order_sn'])->find();
  757. if($extract_data['withdrawal_type']==1){
  758. Db::name('user')->where('uid',$extract_data['uid'])->inc('brokerage_price',$extract_data['extract_price'])->update();
  759. }else{
  760. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$extract_data['order_sn'])->where('pm',2)->find();
  761. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$content['err_code_des']]);
  762. Db::name('entropy_barter_user_'.$extract_data['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$extract_data['extract_price'])->update();
  763. }
  764. return ['code'=>201,'msg'=>$content['err_code_des']];
  765. }
  766. }else{
  767. return ['code'=>200,'msg'=>'未找到数据'];
  768. }
  769. }
  770. //付款到零钱查询
  771. public function WechatTransfers_query($order_sn)
  772. {
  773. // Db::name('log')->insert(['data'=>'微信提现查询走进来了']);
  774. $params["appid"]='wxbf753066ac8686ba';
  775. $params["mch_id"] = '1605734712';
  776. $params["nonce_str"]= mt_rand(100000000,999999999);
  777. $params["partner_trade_no"]= $order_sn;
  778. $sign =$this->getSign($params);
  779. //生成签名
  780. $params['sign'] = $sign;
  781. //构造XML数据
  782. $xmldata = $this->ToXml($params); //数组转XML
  783. $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo';
  784. //发送post请求
  785. $res = $this->curl_post_ssl($url, $xmldata,[]);
  786. if(!$res){
  787. return ['code'=>500,'msg'=>'请求未能发送成功'];
  788. }
  789. //付款结果分析
  790. $content = $this->FromXml($res); //xml转数组
  791. // Db::name('log')->insert(['data'=>'查询'.json_encode($content)]);
  792. try {
  793. if($content['status']=='SUCCESS'){
  794. Db::name('entropy_barter_bill')->where('order_no',$content['partner_trade_no'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  795. Db::name('user_extract')->where('order_sn',$content['partner_trade_no'])->update(['status'=>1]);
  796. //$bill=Db::name('entropy_barter_bill')->where('order_no',$content['partner_trade_no'])->where('pm',2)->find();
  797. //$mer_id=Db::name('user_extract')->where('order_sn',$content['partner_trade_no'])->value('mer_id');
  798. //Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$bill['to_id'])->dec('wallet',$bill['number'])->update();
  799. }
  800. }catch (\Exception $e) {
  801. Db::name('log')->insert(['data'=>'提现到微信查询出错:'.$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】']);
  802. }
  803. }
  804. /**
  805. * @remarks 支付宝付款到零钱
  806. * @author Tang
  807. * @created 2021/9/9 12:59
  808. */
  809. public function AliTransfers($id)
  810. {
  811. try {
  812. $userdata=Db::name('user_extract')
  813. ->where(['extract_id'=>$id])
  814. ->find();
  815. $identity=Db::name('user')->where('uid',$userdata['uid'])->value('ali_user_id');
  816. if($userdata and !empty($userdata)){
  817. $app_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/appCertPublicKey.crt';
  818. $alipay_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayCertPublicKey.crt';
  819. $alipay_root_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayRootCert.crt';
  820. $url = "https://openapi.alipay.com/gateway.do";
  821. $app_id="2021002194632049";
  822. $privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGxceDFVT6VTYClinyAdY4PxE6MadNYLZ3sbLOLV14e39kuu1lkKDBZ/KPRNruPlSPGdiRVe+L8v4rsVk6bthsS/vMk5aH1wQyt58/HvHmZ5QVo3U5UD7cgqqefTcRJjKhjjM1rU/OrOkOqyssaLRukW3jeKRlBccUgtaGsXXrbMxWYpzl1OMDhKRRUVxu3LTfqlMpHghOasQrgyD92q9wlUN7U6hBYzGUocO/N3sz97PZwptwWAW0r3CFdlLCpgnMr+xb/Zh8td1OKGl3wEghiGavgDDlc2+w/xtk1SZ3pJbnGAU+D+oyJ6r76po6vkyGIlLrKp/zQ50az7fObzgNAgMBAAECggEBAK60szERlMkaEAih92gQGTsCo5+keMnX0UjO1LvGv7rfwQ7GBVYZklGrjVRDTrHL8wJ70w+amptFDgVVMXncZzh4aG5c4heu8q+pGLyf9DlwnIWQT736O+YQqun2YGogSqwYkgYBuH2NGKKd66pytPPhutYN+WAZfesXPHrSizRJtZMfuZvvGzm6ZJLZ1LmhvkOuLrX4xrJGRs1nAwZOmOfi4MY5VASblfPj59fUim9hErocNaX4uiMVwmhQl2QuOM/EbTd1UkW+dkV/gyQMOFzpcfN+SEi+hdLN+JiR9TVEcwity6ihOG5+3X33GKzfY4WFxeHHUaqA0SQWSkKofMECgYEA5OF5Imtq8/6JjWJ0jvYCpUnj9742McGJZTWBoTn9Hp0d3bwyE3YbH8pBVJyvzlfPKB9TUjE2FzVZvQtxEu+ZxToccp/LPqlgITWNHCmEtzAgXW7ww2PafgDZJ2QRSyjLUeRIWSAkeilj64XMCEC/bEs/nb5nmUb2gnsNTvvpMLUCgYEA3lMMtaIZH1fMI4XMNaPFzeRiKc0FIcLEem/efnPetPuOCujIWQJ/x9cCDCcfqO59I1FXQuiC/E1dFvme2qs/H7h2bFu8RG0M/ZQWd9twg31Sh+R7gCQakFERag8HXc4AWfBGXCvMu1SmSovU49KecSLxYGOAUdp77j1GxtLiePkCgYAQjc45ExPVOd+w/iH4BQsD8Wgvju5Ugu7xBwGtK4iHIk36r5XfmnczwWkgOYTto6Qz/rAEDdMfspge+CjhebrhbOaJ08zbZ1ywijL+inIy3aQ5ncCEIUC4RE9wbehiSz0JWz1wVMbOnxe+/RpYrnYp2vdq7U6I430IyuWXhNjE0QKBgEtJUmd7oghEIgPxfiq37/b+HOPM4q0BGKnhkjW+JS+idAJru9SwjPbub2oQIZ+CS2wXUnZ86EZqKFjsZQflr7WdMLUXB5UgXKLOcCFcdSiB2t3b2JqXH0u5uCzzM+pnJSVPwXPa/TR+wOVDnu8bVr43OAgNCdouI4OUyo/vv/N5AoGATJaIvpsZ9v1zmhbtJbgPBM9dhD2PIp2ufZ7yvhGGzA02FqAbyAeVsI2d+W+uA6jJ1X87x27pQv//mFoFXStxX3/bhdgTWbUYEWobAhw1jBS1rMQfLuBGGI/LsHGhzau3U+59erC5sYhGgZKSdXDyjOduWQlPWAv6ufkNZ+I3FCU=";
  823. // 证书模式的测试
  824. $alipayConfig = new AlipayConfig();
  825. $alipayConfig->setAppId($app_id);
  826. $alipayConfig->setCharset("utf-8");
  827. $alipayConfig->setFormat("json");
  828. $alipayConfig->setSignType("RSA2");
  829. $alipayConfig->setServerUrl($url);
  830. $alipayConfig->setPrivateKey($privateKey);
  831. // content 和 path 只需要设置一个即可
  832. $alipayConfig->setAppCertPath($app_cert_path);
  833. //$alipayConfig->setAppCertContent()
  834. $alipayConfig->setAlipayPublicCertPath($alipay_cert_path);
  835. //$alipayConfig->setAlipayPublicCertContent()
  836. $alipayConfig->setRootCertPath($alipay_root_cert_path);
  837. //$alipayConfig->setRootCertContent()
  838. $aop = new AopCertClient($alipayConfig);
  839. $aop->isCheckAlipayPublicCert = true;
  840. $order_title='提现';
  841. if($userdata['withdrawal_type']==1){
  842. $order_title='幸福宝提现';
  843. $userdata['extract_price']=bcsub($userdata['extract_price'],$userdata['service_money']);
  844. }elseif($userdata['withdrawal_type']==2){
  845. $mer_name=Db::name('merchant')->where('mer_id',$userdata['mer_id'])->value('mer_name');
  846. $order_title='幸福宝-'.$mer_name.'提现';
  847. $userdata['extract_price']=bcsub($userdata['extract_price'],$userdata['service_money']);
  848. }
  849. // Db::name('log')->insert(['data'=>'AopCertClient']);
  850. $parameter = "{".
  851. "\"out_biz_no\":\"".$userdata['order_sn']."\",".
  852. "\"remark\":\"提现到支付宝\",".
  853. // "\"business_params\"":.json_encode(['payer_show_name_use_alias'=>'北京天地博爱网络科技有限公司']).
  854. "\"business_params\":\"{'payer_show_name_use_alias':'北京天地博爱网络科技有限公司'}\",".
  855. "\"biz_scene\":\"DIRECT_TRANSFER\",".
  856. "\"payee_info\":{".
  857. "\"identity\":\"".$identity."\",".
  858. "\"identity_type\":\"ALIPAY_USER_ID\",".
  859. // "\"name\":\"".$userdata['real_name']."\"".
  860. "},".
  861. "\"trans_amount\":\"".$userdata['extract_price']."\",".
  862. "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",".
  863. "\"order_title\":\"".$order_title."\"".
  864. "}";
  865. $request = new AlipayFundTransUniTransferRequest ();
  866. $request->setBizContent($parameter);
  867. $response = $aop->execute($request);
  868. Db::name('log')->insert(['data'=>'【支付宝提现返回结果】'.$response]);
  869. $response=json_decode($response,true);
  870. if($response['alipay_fund_trans_uni_transfer_response']['code']=='10000'){
  871. return ['code'=>200,'msg'=>'成功'];
  872. }else{
  873. return ['code'=>201,'msg'=>$response['alipay_fund_trans_uni_transfer_response']['sub_msg']];
  874. }
  875. }else{
  876. return ['code'=>200,'msg'=>'未找到数据'];
  877. }
  878. }catch (Exception $exception){
  879. Db::name("log")->insert(array('data'=>$exception->getFile().':'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
  880. }
  881. }
  882. /*
  883. * Effect 微信生成签名
  884. * author tangshiwei
  885. * time 2021-09-09
  886. * */
  887. public function getSign($params) {
  888. ksort($params); //将参数数组按照参数名ASCII码从小到大排序
  889. foreach ($params as $key => $item) {
  890. if (!empty($item)) {
  891. //剔除参数值为空的参数
  892. $newArr[] = $key.'='.$item; // 整合新的参数数组
  893. }
  894. }
  895. $stringA = implode("&", $newArr); //使用 & 符号连接参数
  896. $stringSignTemp = $stringA."&key=70yfchPMifQCESGSFr53vOZmUJZ8Srql";//拼接key
  897. // key是在商户平台API安全里自己设置的
  898. $stringSignTemp = md5($stringSignTemp); //将字符串进行MD5加密
  899. $sign = strtoupper($stringSignTemp); //将所有字符转换为大写
  900. return $sign;
  901. }
  902. /**
  903. * @remarks curl 请求
  904. * @author Tang
  905. * @created 2021/9/9 13:14
  906. */
  907. function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
  908. $dirs= App::getRootPath();
  909. $ch = curl_init();//初始化curl
  910. curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
  911. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
  912. curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
  913. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
  914. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
  915. curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
  916. curl_setopt($ch, CURLOPT_SSLCERT, $dirs.'pkey/cert/apiclient_cert.pem');//证书位置
  917. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
  918. curl_setopt($ch, CURLOPT_SSLKEY, $dirs.'pkey/cert/apiclient_key.pem');//证书位置
  919. if (count($aHeader) >= 1) {
  920. curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
  921. }
  922. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  923. curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送
  924. $data = curl_exec($ch);//执行回话
  925. if ($data) {
  926. curl_close($ch);
  927. return $data;
  928. } else {
  929. $error = curl_errno($ch);
  930. echo "call faild, errorCode:$error\n";
  931. curl_close($ch);
  932. return false;
  933. }
  934. }
  935. /**
  936. * @remarks 数组转xml
  937. * @author Tang
  938. * @created 2021/9/9 13:14
  939. */
  940. public function ToXml($data=array())
  941. {
  942. if(!is_array($data) || count($data) <= 0)
  943. {
  944. return '数组异常';
  945. }
  946. $xml = "<xml>";
  947. foreach ($data as $key=>$val)
  948. {
  949. if (is_numeric($val)){
  950. $xml.="<".$key.">".$val."</".$key.">";
  951. }else{
  952. $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  953. }
  954. }
  955. $xml.="</xml>";
  956. return $xml;
  957. }
  958. /**
  959. * @remarks xml转数组
  960. * @author Tang
  961. * @created 2021/9/9 13:15
  962. */
  963. public function FromXml($xml)
  964. {
  965. if(!$xml){
  966. echo "xml数据异常!";
  967. }
  968. //将XML转为array
  969. //禁止引用外部xml实体
  970. libxml_disable_entity_loader(true);
  971. $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  972. return $data;
  973. }
  974. public function band_account($type,$account,$info,$uid){
  975. $accountinfo=Db::name("user_withdraw_account")->where(["account_type"=>$type,"user_id"=>$uid])->find();
  976. $data=[
  977. "account_type"=>$type,
  978. "account"=>$account,
  979. "info"=>$info,
  980. 'update_time'=>date("Y-m-d H:i:s"),
  981. ];
  982. if ($accountinfo){
  983. Db::name("user_withdraw_account")->where("id",$accountinfo["id"])->update($data);
  984. }else{
  985. $data["user_id"]=$uid;
  986. $data["create_time"]=date("Y-m-d H:i:s");
  987. Db::name("user_withdraw_account")->insert($data);
  988. }
  989. return ["msg"=>'绑定成功'];
  990. }
  991. public function band_openid($openid,$uid){
  992. $user_data["wechat_user_id"]=$openid;
  993. $user_count=Db::name('user')->where($user_data)->count();
  994. if($user_count>0){
  995. return true;
  996. }
  997. $data["openid"]=$openid;
  998. $count=Db::name("user_extract_openid")->where($data)->count();
  999. if($count>0){
  1000. return false;
  1001. }
  1002. $data["uid"]=$uid;
  1003. $wx_type=input("wx_type/d",0);
  1004. $data["type"]=$wx_type==1?1:0;
  1005. Db::name("user_extract_openid")->insert($data);
  1006. return true;
  1007. // return ["msg"=>'绑定成功'];
  1008. }
  1009. /*获取绑卡账户*/
  1010. public function band_account_info($type,$uid){
  1011. if($type=='1'){
  1012. $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
  1013. if(!$res){
  1014. return false;
  1015. }
  1016. return true;
  1017. }
  1018. $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
  1019. if($res && $res != '0' && $res != ''){
  1020. return true;
  1021. }
  1022. return false;
  1023. // $account=Db::name("user_withdraw_account")->where(["account_type"=>$type,"user_id"=>$uid])->find();//
  1024. //
  1025. // if ($account){
  1026. // if($account['account_type'] ==3){
  1027. // $account['icon'] = '';
  1028. // }
  1029. // return $account;
  1030. // }else{
  1031. // return false;
  1032. // }
  1033. }
  1034. public function listBank($where)
  1035. {
  1036. return Db::name("user_withdraw_account")->where($where)->order('id desc')->select();
  1037. }
  1038. /*添加银行卡*/
  1039. public function createBank($data){
  1040. $data["account_type"] = 3;
  1041. $data["info"] = $data['user_name'];
  1042. $real_name = $this->real_info($data['user_id']);
  1043. if(!$real_name){
  1044. return ['code'=>400,'msg'=>'请先实名认证'];
  1045. }
  1046. if($real_name['user_name'] != $data['user_name']){
  1047. return ['code'=>400,'msg'=>'认证信息与银行卡绑定用户不符'];
  1048. }
  1049. if(Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->value("id")){
  1050. //操作修改
  1051. $data['update_time'] = date("Y-m-d H:i:s");
  1052. Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->update($data);
  1053. return Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->value("id");
  1054. // return ['code'=>400,'msg'=>'只能绑定一张银行卡'];
  1055. }
  1056. $data['create_time'] = date("Y-m-d H:i:s");
  1057. return Db::name("user_withdraw_account")->insertGetId($data);
  1058. }
  1059. /*修改银行卡*/
  1060. public function saveBank($where=[],$data=[]){
  1061. $data['update_time'] = date("Y-m-d H:i:s");
  1062. $res = Db::name("user_withdraw_account")->where($where)->update($data);
  1063. return $res;
  1064. }
  1065. /*银行卡列表*/
  1066. public function list($where=[]){
  1067. $res = Db::name("user_withdraw_account")->where($where)->select();
  1068. return $res;
  1069. }
  1070. /*用户认证信息*/
  1071. public function real_info($uid){
  1072. $data = Db::name("user_certification")->where(["uid"=>$uid,'status'=>1])->find();
  1073. return $data;
  1074. }
  1075. }