UserExtractRepository.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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){
  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($extract_price_yihu>0){
  385. $insertAll[]=array(
  386. 'extract_id'=>$extract->extract_id,
  387. 'uid'=> $data['uid'],
  388. 'extract_type'=> $data["extract_type"],
  389. 'extract_price'=> $extract_price_yihu,
  390. 'service_money'=> $service_money_yihu,
  391. 'order_sn'=> $data['order_sn'],
  392. 'type'=> 1,//0- 储蓄保 1-一壶茶
  393. );
  394. // }
  395. $insertAll[]=array(
  396. 'extract_id'=>$extract->extract_id,
  397. 'uid'=> $data['uid'],
  398. 'extract_type'=> $data["extract_type"],
  399. 'extract_price'=> ($data['extract_price']-$extract_price_yihu),
  400. 'service_money'=> ($data['service_money']-$service_money_yihu),
  401. 'order_sn'=> $data['order_sn'],
  402. 'type'=> 0,//0- 储蓄保 1-一壶茶
  403. );
  404. DB::name('user_extract_item')->insertAll($insertAll);
  405. return $extract;
  406. });
  407. }
  408. SwooleTaskService::admin('notice', [
  409. 'type' => 'extract',
  410. 'title' => '您有一条新的提醒申请',
  411. 'id' => $data->extract_id
  412. ]);
  413. return true;
  414. }
  415. public function create_yhc($user, $merchant, $data)
  416. {
  417. Db::name("merchant")->where("mer_id", $merchant['mer_id'])->dec('brokerage_price', $data['extract_price'])->update();
  418. $data["bank_code"]=$merchant["bank_account"];
  419. $data["bank_address"]=$merchant["bank_deposit"];
  420. $data['order_sn'] = 'tx'.time().rand(100000, 999999);
  421. $data["real_name"]=$user['nickname'];
  422. $data['status'] = 0;
  423. $data['uid'] = $user['uid'];
  424. $data['types'] = 1;
  425. $data['type'] = 1;
  426. $data['mer_id'] = $merchant['mer_id'];
  427. $data['withdrawal_type'] =3;
  428. return $this->dao->create($data);
  429. }
  430. public function switchStatus($id,$data)
  431. {
  432. Db::transaction(function()use($id,$data){
  433. if($data['status'] == '-1'){
  434. $extract = $this->dao->getWhere(['extract_id' => $id]);
  435. $user = app()->make(UserRepository::class)->get($extract['uid']);
  436. if (!empty($extract['mer_id'])) {
  437. //商户提现逻辑处理
  438. $mer = app()->make(MerchantRepository::class)->get($extract['mer_id']);
  439. $brokerage_price = bcadd($mer['brokerage_price'] ,$extract['extract_price'],2);
  440. $mer->brokerage_price = $brokerage_price;
  441. $mer->save();
  442. } else {
  443. //用户提现逻辑处理
  444. if($extract['types']==1){
  445. $brokerage_price = bcadd($user['brokerage_price'] ,$extract['extract_price'],2);
  446. //返回余额
  447. $user->brokerage_price = $brokerage_price;
  448. }else{
  449. $member_brokerage_price = bcadd($user['member_brokerage_price'] ,$extract['extract_price'],2);
  450. //返回余额
  451. $user->member_brokerage_price = $member_brokerage_price;
  452. Db::name('user_rich')->where('uid',$extract['uid'])->inc('red', $extract['extract_price'])->update();
  453. Db::name('user_rich_log')->insert([
  454. 'uid' => $extract['uid'],
  455. 'red' => $extract['extract_price'],
  456. 'pm' => 1,
  457. 'time' => time(),
  458. 'order_id' => 0,
  459. 'mark' => '提现失败返还红积分'
  460. ]);
  461. }
  462. $user->save();
  463. }
  464. // //返回积分
  465. // $user->score = bcadd($user['score'] ,$extract['extract_price'],2);
  466. // $user->save();
  467. // Db::name('user_sign_score')->where("order_type","extract") -> where("order_id",$id) -> update(['status'=>0]);
  468. }else{
  469. //积分扣除
  470. // Db::name('user_sign_score')->where("order_type","extract") -> where("order_id",$id) -> update(['status'=>1]);
  471. }
  472. $this->dao->update($id,$data);
  473. });
  474. Queue::push(SendTemplateMessageJob::class,[
  475. 'tempCode' => 'ORDER_DELIVER_SUCCESS',
  476. 'id' =>$id
  477. ]);
  478. }
  479. /**
  480. * @remarks 微信商家转账到零钱
  481. * @author Tang
  482. * @created 2023/10/31
  483. */
  484. public function WechatTransfers($id)
  485. {
  486. $userdata=Db::name('user_extract')
  487. ->alias('u_e')
  488. ->leftJoin('user_extract_openid u_e_o','u_e.uid=u_e_o.uid')
  489. ->where(['extract_id' => $id,'extract_type'=>1])
  490. ->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')
  491. ->find();
  492. if($userdata and !empty($userdata)){
  493. if($userdata['withdrawal_type']==2){
  494. $money= bcsub($userdata['extract_price'],$userdata['service_money'],2);
  495. }else{
  496. $money= bcsub($userdata['extract_price'],$userdata['service_money'],2);
  497. }
  498. // $money=$userdata['extract_price'];//测试不加手续手续费
  499. $res=$this->transfer('提现到微信零钱', $userdata['order_sn'], $money, $userdata['openid'],$userdata['u_e_o_type']);
  500. if(isset($res['code']) && isset($res['message'])) {
  501. return ['code'=>500,'msg'=>$res['message']];
  502. }else{
  503. Db::name('user_extract')->where('extract_id',$id)->update(['wx_status'=>1]);
  504. return ['code'=>201,'msg'=>'微信正在处理'];
  505. }
  506. // else if($res['batch_status']=='ACCEPTED' || $res['batch_status']=='PROCESSING'){
  507. // Db::name('user_extract')->where('extract_id',$id)->update(['wx_status'=>1]);
  508. // return ['code'=>201,'msg'=>'微信正在处理'];
  509. // }else if($res['batch_status']=='FINISHED'){
  510. // //FINISHED:已完成。批次内的所有转账明细单都已处理完成
  511. // Db::name('entropy_barter_bill')->where('order_no', $userdata['order_sn'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  512. // Db::name('user_extract')->where('extract_id',$id)->update(['status'=>1]);
  513. // return ['code'=>200,'msg'=>'审核成功'];
  514. // }
  515. // return ['code'=>500,'msg'=>'提现错误'];
  516. }else{
  517. return ['code'=>200,'msg'=>'未找到数据'];
  518. }
  519. }
  520. /**
  521. * 定时任务3分钟查询一次审核中的微信待处理的订单
  522. * @return array|bool
  523. * @throws \think\db\exception\DataNotFoundException
  524. * @throws \think\db\exception\DbException
  525. * @throws \think\db\exception\ModelNotFoundException
  526. */
  527. public function wechat_extract(){
  528. $user_extract_data=Db::name('user_extract')->where('wx_status',1)->where('status',0)->select();
  529. foreach ($user_extract_data as $v){
  530. $data=$this->batch_id($v['order_sn']);
  531. Db::name('log')->insert(['data'=>'微信审核------'.json_encode($data)]);
  532. if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='FINISHED' && $data['transfer_batch']['success_num']==1){
  533. Db::name('entropy_barter_bill')->where('order_no', $v['order_sn'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  534. Db::name('user_extract')->where('extract_id',$v['extract_id'])->update(['status'=>1]);
  535. }else if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='FINISHED' && $data['transfer_batch']['success_num']<1){
  536. $fail_msg='微信二次审核已驳回';
  537. 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']);
  538. if($v['withdrawal_type']==1){
  539. Db::name('user')->where('uid',$v['uid'])->inc('brokerage_price',$v['extract_price'])->update();
  540. }else{
  541. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$v['order_sn'])->where('pm',2)->find();
  542. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$fail_msg]);
  543. Db::name('entropy_barter_user_'.$v['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$v['extract_price'])->update();
  544. }
  545. }else if(isset($data['transfer_batch']['batch_status']) && $data['transfer_batch']['batch_status']=='CLOSED'){
  546. $fail_msg=(isset($data['transfer_batch']['close_reason']) && $data['transfer_batch']['close_reason']!='')?$data['transfer_batch']['close_reason']:'系统超时未审核,已取消';
  547. 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']);
  548. if($v['withdrawal_type']==1){
  549. Db::name('user')->where('uid',$v['uid'])->inc('brokerage_price',$v['extract_price'])->update();
  550. }else{
  551. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$v['order_sn'])->where('pm',2)->find();
  552. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$fail_msg]);
  553. Db::name('entropy_barter_user_'.$v['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$v['extract_price'])->update();
  554. }
  555. }
  556. }
  557. return true;
  558. }
  559. /**
  560. * 商家转账到零钱(公众号:程序员在囧途)
  561. * @param $batch_name
  562. * @param $out_trade_no
  563. * @param $money
  564. * @param $openid
  565. */
  566. private function transfer($batch_name, $out_trade_no, $money, $openid,$type=0)
  567. {
  568. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  569. $pars = [];
  570. if($type==1){
  571. $pars['appid'] = $this->wxapp['applet_app_id'];//直连商户的appid 小程序的
  572. }else{
  573. $pars['appid'] = $this->wxapp['app_id'];//直连商户的appid APP的
  574. }
  575. $pars['out_batch_no'] = $out_trade_no;//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
  576. $pars['batch_name'] = $batch_name;//该笔批量转账的名称
  577. $pars['batch_remark'] = $batch_name;//转账说明,UTF8编码,最多允许32个字符
  578. $pars['total_amount'] = intval($money * 100);//转账总金额 单位为“分”
  579. $pars['total_num'] = 1;//转账总笔数
  580. $pars['transfer_detail_list'][0] = [
  581. 'out_detail_no' => 'transfer' . $out_trade_no,
  582. 'transfer_amount' => $pars['total_amount'],
  583. 'transfer_remark' => $batch_name,
  584. 'openid' => $openid
  585. ];//转账明细列表
  586. $token = $this->getToken($url,$pars);//获取token
  587. $res = $this->https_request($url, json_encode($pars), $token);//发送请求
  588. return json_decode($res, true);
  589. }
  590. /**
  591. * 通过商家批次单号查询批次单
  592. * @param $order_sn
  593. * @return mixed
  594. *
  595. * 【批次状态】 ACCEPTED:已受理。批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。商户可查询账户资金流水,若该笔转账批次单的扣款已经发生,则表示批次已经进入转账中,请再次查单确认
  596. * PROCESSING:转账中。已开始处理批次内的转账明细单
  597. * FINISHED:已完成。批次内的所有转账明细单都已处理完成
  598. * CLOSED:已关闭。可查询具体的批次关闭原因确认
  599. */
  600. private function batch_id($order_sn)
  601. {
  602. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$order_sn.'?need_query_detail=false';
  603. $token = $this->getToken($url,null,'GET');//获取token
  604. $res = $this->https_request($url, null, $token);//发送请求
  605. return json_decode($res, true);
  606. }
  607. private function https_request($url, $data = null, $token)
  608. {
  609. $curl = curl_init();
  610. curl_setopt($curl, CURLOPT_URL, (string)$url);
  611. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  612. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  613. if (!empty($data)) {
  614. curl_setopt($curl, CURLOPT_POST, 1);
  615. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  616. }
  617. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  618. //添加请求头
  619. $headers = [
  620. 'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token,
  621. 'Accept: application/json',
  622. 'Content-Type: application/json; charset=utf-8',
  623. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  624. ];
  625. if (!empty($headers)) {
  626. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  627. }
  628. $output = curl_exec($curl);
  629. curl_close($curl);
  630. return $output;
  631. }
  632. private function getToken($url,$pars,$http_method='POST')
  633. {
  634. // $http_method = $http_method;//请求方法(GET,POST,PUT)
  635. $timestamp = time();//请求时间戳
  636. $url_parts = parse_url($url);//获取请求的绝对URL
  637. $nonce = $timestamp . rand('10000', '99999');//请求随机串
  638. if($pars){
  639. $body = json_encode((object)$pars);//请求报文主体
  640. }else{
  641. $body = '';
  642. }
  643. $stream_opts = [
  644. "ssl" => [
  645. "verify_peer" => false,
  646. "verify_peer_name" => false,
  647. ]
  648. ];
  649. // try {
  650. $filePath = App::getRootPath();
  651. $certPem= [
  652. 'certPem' => $filePath . $this->wxapp['certPem'],
  653. 'keyPem' => $filePath . $this->wxapp['keyPem'],
  654. ];
  655. $apiclient_cert_path = $certPem['certPem'];
  656. $apiclient_key_path = $certPem['keyPem'];
  657. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path, false, stream_context_create($stream_opts)));
  658. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  659. $mch_private_key = file_get_contents($apiclient_key_path, false, stream_context_create($stream_opts));//密钥
  660. $merchant_id = $this->wxapp['mchid'];
  661. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  662. $message = $http_method . "\n" .
  663. $canonical_url . "\n" .
  664. $timestamp . "\n" .
  665. $nonce . "\n" .
  666. $body . "\n";
  667. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  668. $sign = base64_encode($raw_sign);//签名
  669. // $schema = 'WECHATPAY2-SHA256-RSA2048';
  670. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  671. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  672. // } catch (\Exception $e) {
  673. // throw new \Exception(['msg' => $e->getMessage()]);
  674. // }
  675. return $token;
  676. }
  677. /**
  678. * 企业付款到零钱
  679. * @param $id
  680. * @return array
  681. * @throws \think\db\exception\DataNotFoundException
  682. * @throws \think\db\exception\DbException
  683. * @throws \think\db\exception\ModelNotFoundException
  684. */
  685. public function WechatTransfers_qiye($id)
  686. {
  687. // $extract = $this->dao->getWhere(['extract_id' => $id]);
  688. $userdata=Db::name('user_extract')
  689. ->alias('u_e')
  690. ->leftJoin('user_extract_openid u_e_o','u_e.uid=u_e_o.uid')
  691. ->where(['extract_id' => $id,'extract_type'=>1])
  692. ->field('u_e.extract_price,u_e.uid,u_e_o.openid,u_e.service_money,u_e.withdrawal_type,u_e.order_sn')
  693. ->find();
  694. if($userdata and !empty($userdata)){
  695. $params["mch_appid"]='wxbf753066ac8686ba';
  696. $params["mchid"] = '1605734712';
  697. $params["nonce_str"]= mt_rand(100000000,999999999);
  698. $params["partner_trade_no"] = $userdata['order_sn'];
  699. if($userdata['withdrawal_type']==2){
  700. $params["amount"]= bcmul(bcsub($userdata['extract_price'],$userdata['service_money'],2),100);
  701. }else{
  702. $params["amount"]= bcmul(bcsub($userdata['extract_price'],$userdata['service_money'],2),100);
  703. }
  704. $params["desc"]= '提现到微信零钱';
  705. $params["openid"]= $userdata['openid'];
  706. $params["check_name"]= 'NO_CHECK';
  707. $sign =$this->getSign($params);
  708. //生成签名
  709. $params['sign'] = $sign;
  710. //构造XML数据
  711. $xmldata = $this->ToXml($params); //数组转XML
  712. $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  713. //发送post请求
  714. $res = $this->curl_post_ssl($url, $xmldata,[]);
  715. // Db::name('log')->insert(['data'=>json_encode($res)]);
  716. if(!$res){
  717. return ['code'=>500,'msg'=>'请求未能发送成功'];
  718. }
  719. //付款结果分析
  720. $content = $this->FromXml($res); //xml转数组
  721. Db::name('log')->insert(['data'=>'【微信提现返回】'.json_encode($content)]);
  722. if($content['result_code']=="SUCCESS"){
  723. $this->WechatTransfers_query($userdata['order_sn']);
  724. return ['code'=>200,'msg'=>'成功'];
  725. }else{
  726. // Db::name('log')->insert(['data'=>'else进来了']);
  727. 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']);
  728. $extract_data=Db::name('user_extract')->where('order_sn',$userdata['order_sn'])->find();
  729. if($extract_data['withdrawal_type']==1){
  730. Db::name('user')->where('uid',$extract_data['uid'])->inc('brokerage_price',$extract_data['extract_price'])->update();
  731. }else{
  732. $eb_bill=Db::name('entropy_barter_bill')->where('order_no',$extract_data['order_sn'])->where('pm',2)->find();
  733. Db::name('entropy_barter_bill')->where('id',$eb_bill['id'])->where('pm',2)->update(['status'=>3,'remarks'=>$content['err_code_des']]);
  734. Db::name('entropy_barter_user_'.$extract_data['mer_id'])->where('eb_id',$eb_bill['to_id'])->inc('wallet',$extract_data['extract_price'])->update();
  735. }
  736. return ['code'=>201,'msg'=>$content['err_code_des']];
  737. }
  738. }else{
  739. return ['code'=>200,'msg'=>'未找到数据'];
  740. }
  741. }
  742. //付款到零钱查询
  743. public function WechatTransfers_query($order_sn)
  744. {
  745. // Db::name('log')->insert(['data'=>'微信提现查询走进来了']);
  746. $params["appid"]='wxbf753066ac8686ba';
  747. $params["mch_id"] = '1605734712';
  748. $params["nonce_str"]= mt_rand(100000000,999999999);
  749. $params["partner_trade_no"]= $order_sn;
  750. $sign =$this->getSign($params);
  751. //生成签名
  752. $params['sign'] = $sign;
  753. //构造XML数据
  754. $xmldata = $this->ToXml($params); //数组转XML
  755. $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo';
  756. //发送post请求
  757. $res = $this->curl_post_ssl($url, $xmldata,[]);
  758. if(!$res){
  759. return ['code'=>500,'msg'=>'请求未能发送成功'];
  760. }
  761. //付款结果分析
  762. $content = $this->FromXml($res); //xml转数组
  763. // Db::name('log')->insert(['data'=>'查询'.json_encode($content)]);
  764. try {
  765. if($content['status']=='SUCCESS'){
  766. Db::name('entropy_barter_bill')->where('order_no',$content['partner_trade_no'])->where('pm',2)->update(['status'=>2,'remarks'=>'已到账']);
  767. Db::name('user_extract')->where('order_sn',$content['partner_trade_no'])->update(['status'=>1]);
  768. //$bill=Db::name('entropy_barter_bill')->where('order_no',$content['partner_trade_no'])->where('pm',2)->find();
  769. //$mer_id=Db::name('user_extract')->where('order_sn',$content['partner_trade_no'])->value('mer_id');
  770. //Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$bill['to_id'])->dec('wallet',$bill['number'])->update();
  771. }
  772. }catch (\Exception $e) {
  773. Db::name('log')->insert(['data'=>'提现到微信查询出错:'.$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】']);
  774. }
  775. }
  776. /**
  777. * @remarks 支付宝付款到零钱
  778. * @author Tang
  779. * @created 2021/9/9 12:59
  780. */
  781. public function AliTransfers($id)
  782. {
  783. try {
  784. $userdata=Db::name('user_extract')
  785. ->where(['extract_id'=>$id])
  786. ->find();
  787. $identity=Db::name('user')->where('uid',$userdata['uid'])->value('ali_user_id');
  788. if($userdata and !empty($userdata)){
  789. $app_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/appCertPublicKey.crt';
  790. $alipay_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayCertPublicKey.crt';
  791. $alipay_root_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayRootCert.crt';
  792. $url = "https://openapi.alipay.com/gateway.do";
  793. $app_id="2021002194632049";
  794. $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=";
  795. // 证书模式的测试
  796. $alipayConfig = new AlipayConfig();
  797. $alipayConfig->setAppId($app_id);
  798. $alipayConfig->setCharset("utf-8");
  799. $alipayConfig->setFormat("json");
  800. $alipayConfig->setSignType("RSA2");
  801. $alipayConfig->setServerUrl($url);
  802. $alipayConfig->setPrivateKey($privateKey);
  803. // content 和 path 只需要设置一个即可
  804. $alipayConfig->setAppCertPath($app_cert_path);
  805. //$alipayConfig->setAppCertContent()
  806. $alipayConfig->setAlipayPublicCertPath($alipay_cert_path);
  807. //$alipayConfig->setAlipayPublicCertContent()
  808. $alipayConfig->setRootCertPath($alipay_root_cert_path);
  809. //$alipayConfig->setRootCertContent()
  810. $aop = new AopCertClient($alipayConfig);
  811. $aop->isCheckAlipayPublicCert = true;
  812. $order_title='提现';
  813. if($userdata['withdrawal_type']==1){
  814. $order_title='储蓄保提现';
  815. $userdata['extract_price']=bcsub($userdata['extract_price'],$userdata['service_money']);
  816. }elseif($userdata['withdrawal_type']==2){
  817. $mer_name=Db::name('merchant')->where('mer_id',$userdata['mer_id'])->value('mer_name');
  818. $order_title='储蓄保-'.$mer_name.'提现';
  819. $userdata['extract_price']=bcsub($userdata['extract_price'],$userdata['service_money']);
  820. }
  821. // Db::name('log')->insert(['data'=>'AopCertClient']);
  822. $parameter = "{".
  823. "\"out_biz_no\":\"".$userdata['order_sn']."\",".
  824. "\"remark\":\"提现到支付宝\",".
  825. // "\"business_params\"":.json_encode(['payer_show_name_use_alias'=>'北京天地博爱网络科技有限公司']).
  826. "\"business_params\":\"{'payer_show_name_use_alias':'北京天地博爱网络科技有限公司'}\",".
  827. "\"biz_scene\":\"DIRECT_TRANSFER\",".
  828. "\"payee_info\":{".
  829. "\"identity\":\"".$identity."\",".
  830. "\"identity_type\":\"ALIPAY_USER_ID\",".
  831. // "\"name\":\"".$userdata['real_name']."\"".
  832. "},".
  833. "\"trans_amount\":\"".$userdata['extract_price']."\",".
  834. "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",".
  835. "\"order_title\":\"".$order_title."\"".
  836. "}";
  837. $request = new AlipayFundTransUniTransferRequest ();
  838. $request->setBizContent($parameter);
  839. $response = $aop->execute($request);
  840. Db::name('log')->insert(['data'=>'【支付宝提现返回结果】'.$response]);
  841. $response=json_decode($response,true);
  842. if($response['alipay_fund_trans_uni_transfer_response']['code']=='10000'){
  843. return ['code'=>200,'msg'=>'成功'];
  844. }else{
  845. return ['code'=>201,'msg'=>$response['alipay_fund_trans_uni_transfer_response']['sub_msg']];
  846. }
  847. }else{
  848. return ['code'=>200,'msg'=>'未找到数据'];
  849. }
  850. }catch (Exception $exception){
  851. Db::name("log")->insert(array('data'=>$exception->getFile().':'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
  852. }
  853. }
  854. /*
  855. * Effect 微信生成签名
  856. * author tangshiwei
  857. * time 2021-09-09
  858. * */
  859. public function getSign($params) {
  860. ksort($params); //将参数数组按照参数名ASCII码从小到大排序
  861. foreach ($params as $key => $item) {
  862. if (!empty($item)) {
  863. //剔除参数值为空的参数
  864. $newArr[] = $key.'='.$item; // 整合新的参数数组
  865. }
  866. }
  867. $stringA = implode("&", $newArr); //使用 & 符号连接参数
  868. $stringSignTemp = $stringA."&key=70yfchPMifQCESGSFr53vOZmUJZ8Srql";//拼接key
  869. // key是在商户平台API安全里自己设置的
  870. $stringSignTemp = md5($stringSignTemp); //将字符串进行MD5加密
  871. $sign = strtoupper($stringSignTemp); //将所有字符转换为大写
  872. return $sign;
  873. }
  874. /**
  875. * @remarks curl 请求
  876. * @author Tang
  877. * @created 2021/9/9 13:14
  878. */
  879. function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
  880. $dirs= App::getRootPath();
  881. $ch = curl_init();//初始化curl
  882. curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
  883. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
  884. curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
  885. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
  886. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
  887. curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
  888. curl_setopt($ch, CURLOPT_SSLCERT, $dirs.'pkey/cert/apiclient_cert.pem');//证书位置
  889. curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
  890. curl_setopt($ch, CURLOPT_SSLKEY, $dirs.'pkey/cert/apiclient_key.pem');//证书位置
  891. if (count($aHeader) >= 1) {
  892. curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
  893. }
  894. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  895. curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送
  896. $data = curl_exec($ch);//执行回话
  897. if ($data) {
  898. curl_close($ch);
  899. return $data;
  900. } else {
  901. $error = curl_errno($ch);
  902. echo "call faild, errorCode:$error\n";
  903. curl_close($ch);
  904. return false;
  905. }
  906. }
  907. /**
  908. * @remarks 数组转xml
  909. * @author Tang
  910. * @created 2021/9/9 13:14
  911. */
  912. public function ToXml($data=array())
  913. {
  914. if(!is_array($data) || count($data) <= 0)
  915. {
  916. return '数组异常';
  917. }
  918. $xml = "<xml>";
  919. foreach ($data as $key=>$val)
  920. {
  921. if (is_numeric($val)){
  922. $xml.="<".$key.">".$val."</".$key.">";
  923. }else{
  924. $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  925. }
  926. }
  927. $xml.="</xml>";
  928. return $xml;
  929. }
  930. /**
  931. * @remarks xml转数组
  932. * @author Tang
  933. * @created 2021/9/9 13:15
  934. */
  935. public function FromXml($xml)
  936. {
  937. if(!$xml){
  938. echo "xml数据异常!";
  939. }
  940. //将XML转为array
  941. //禁止引用外部xml实体
  942. libxml_disable_entity_loader(true);
  943. $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  944. return $data;
  945. }
  946. public function band_account($type,$account,$info,$uid){
  947. $accountinfo=Db::name("user_withdraw_account")->where(["account_type"=>$type,"user_id"=>$uid])->find();
  948. $data=[
  949. "account_type"=>$type,
  950. "account"=>$account,
  951. "info"=>$info,
  952. 'update_time'=>date("Y-m-d H:i:s"),
  953. ];
  954. if ($accountinfo){
  955. Db::name("user_withdraw_account")->where("id",$accountinfo["id"])->update($data);
  956. }else{
  957. $data["user_id"]=$uid;
  958. $data["create_time"]=date("Y-m-d H:i:s");
  959. Db::name("user_withdraw_account")->insert($data);
  960. }
  961. return ["msg"=>'绑定成功'];
  962. }
  963. public function band_openid($openid,$uid){
  964. $user_data["wechat_user_id"]=$openid;
  965. $user_count=Db::name('user')->where($user_data)->count();
  966. if($user_count>0){
  967. return true;
  968. }
  969. $data["openid"]=$openid;
  970. $count=Db::name("user_extract_openid")->where($data)->count();
  971. if($count>0){
  972. return false;
  973. }
  974. $data["uid"]=$uid;
  975. $wx_type=input("wx_type/d",0);
  976. $data["type"]=$wx_type==1?1:0;
  977. Db::name("user_extract_openid")->insert($data);
  978. return true;
  979. // return ["msg"=>'绑定成功'];
  980. }
  981. /*获取绑卡账户*/
  982. public function band_account_info($type,$uid){
  983. if($type=='1'){
  984. $res=Db::name('user_extract_openid')->where('uid',$uid)->value('openid');
  985. if(!$res){
  986. return false;
  987. }
  988. return true;
  989. }
  990. $res = Db::name('user') -> where('uid',$uid) -> value('ali_user_id');
  991. if($res && $res != '0' && $res != ''){
  992. return true;
  993. }
  994. return false;
  995. // $account=Db::name("user_withdraw_account")->where(["account_type"=>$type,"user_id"=>$uid])->find();//
  996. //
  997. // if ($account){
  998. // if($account['account_type'] ==3){
  999. // $account['icon'] = '';
  1000. // }
  1001. // return $account;
  1002. // }else{
  1003. // return false;
  1004. // }
  1005. }
  1006. public function listBank($where)
  1007. {
  1008. return Db::name("user_withdraw_account")->where($where)->order('id desc')->select();
  1009. }
  1010. /*添加银行卡*/
  1011. public function createBank($data){
  1012. $data["account_type"] = 3;
  1013. $data["info"] = $data['user_name'];
  1014. $real_name = $this->real_info($data['user_id']);
  1015. if(!$real_name){
  1016. return ['code'=>400,'msg'=>'请先实名认证'];
  1017. }
  1018. if($real_name['user_name'] != $data['user_name']){
  1019. return ['code'=>400,'msg'=>'认证信息与银行卡绑定用户不符'];
  1020. }
  1021. if(Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->value("id")){
  1022. //操作修改
  1023. $data['update_time'] = date("Y-m-d H:i:s");
  1024. Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->update($data);
  1025. return Db::name("user_withdraw_account")->where(['user_id'=>$data['user_id'],'account_type'=>3,'status'=>0])->value("id");
  1026. // return ['code'=>400,'msg'=>'只能绑定一张银行卡'];
  1027. }
  1028. $data['create_time'] = date("Y-m-d H:i:s");
  1029. return Db::name("user_withdraw_account")->insertGetId($data);
  1030. }
  1031. /*修改银行卡*/
  1032. public function saveBank($where=[],$data=[]){
  1033. $data['update_time'] = date("Y-m-d H:i:s");
  1034. $res = Db::name("user_withdraw_account")->where($where)->update($data);
  1035. return $res;
  1036. }
  1037. /*银行卡列表*/
  1038. public function list($where=[]){
  1039. $res = Db::name("user_withdraw_account")->where($where)->select();
  1040. return $res;
  1041. }
  1042. /*用户认证信息*/
  1043. public function real_info($uid){
  1044. $data = Db::name("user_certification")->where(["uid"=>$uid,'status'=>1])->find();
  1045. return $data;
  1046. }
  1047. }