User.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018-2020 rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: TABLE ME
  8. // +----------------------------------------------------------------------
  9. // | Date: 2020-08-25 17:23
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\controller;
  13. use app\BaseController;
  14. use app\model\api\User as UserModel;
  15. use app\model\api\UserDetail as UserDetailModel;
  16. use app\model\api\ServiceType as ServiceTypeModel;
  17. use app\model\api\InfoAudit;
  18. use app\model\api\TypeAudit;
  19. use app\model\api\UserAudit;
  20. use app\model\api\ServiceType;
  21. use app\model\api\ServiceLabel as ServiceLabelModel;
  22. use app\model\api\ServiceTimeType;
  23. use app\model\api\City as CityModel;
  24. use app\model\api\Sys as SysModel;
  25. use app\model\api\ShowTemplate;
  26. use app\model\api\ShowTemplateOrder;
  27. use app\model\api\UserShowTemplate;
  28. use app\model\api\UserWorkType;
  29. use app\model\api\PayTrade as PayTradeModel;
  30. use app\api\controller\pub;
  31. use app\Request;
  32. use library\services\UtilService;
  33. use library\utils\QRcodeComm;
  34. use library\utils\Qiniu;
  35. use library\utils\IdentityCard;
  36. use library\utils\WxpayV2 as wxpayApi;
  37. use think\db\exception\DbException;
  38. use library\lib\weixina;
  39. use think\facade\Db;
  40. use think\Image;
  41. use think\Route;
  42. class User extends BaseController
  43. {
  44. /**
  45. * 获取用户详情
  46. * @param Request $request
  47. */
  48. public function userInfo(Request $request){
  49. //资料审核信息
  50. $infoAuditData = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  51. $userAuditData = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  52. $typeAuditData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  53. $data = [];
  54. $data['uid'] = $request->user['uid'];
  55. $data['nickname'] = $request->user['nickname'];
  56. $data['mobile'] = $request->user['mobile'];
  57. $data['avatar'] = $request->user['avatar'];
  58. $data['name'] = $request->user['name'];
  59. $data['sex'] = $request->user['sex'];
  60. $data['type'] = $request->user['type'];//用户类型
  61. $data['type_name'] = "";//用户类型名称
  62. $data['work_type_id'] = $request->user['work_type_id'];//用户职称类型
  63. $data['work_type_title'] = $request->user['work_type_title'];//用户职称类型名称
  64. $data['card_look_count'] = $request->user['card_look_count'];//用户名片浏览次数
  65. $data['info_audit_status'] = empty($infoAuditData)?-2:$infoAuditData["status"];
  66. $data['user_audit_status'] = empty($userAuditData)?-2:$userAuditData["status"];
  67. $data['type_audit_status'] = empty($typeAuditData)?-2:$typeAuditData["status"];
  68. //资料通过需要重新提交认证
  69. if(!empty($infoAuditData) && !empty($typeAuditData)){
  70. if($infoAuditData["status"]==1 && $typeAuditData["status"]==1 && $infoAuditData["admin_time"]>$typeAuditData["admin_time"]){
  71. $data['type_audit_status'] = -3;
  72. }
  73. }
  74. $data['show_template_code'] = "";
  75. $data['show_template_id'] = "";
  76. $tmpData = (new UserShowTemplate)
  77. ->field("t.id,t.code,t.title,t.is_init,b.is_default")
  78. ->alias("b")
  79. ->join("show_template t","t.id = b.show_template_id","left")
  80. ->where("b.uid",$request->user['uid'])
  81. ->order("b.is_default","desc")
  82. ->order("b.id","desc")
  83. ->find();
  84. if(!empty($tmpData)){
  85. $data['show_template_code'] = $tmpData["code"];
  86. $data['show_template_id'] = $tmpData["id"];
  87. $data['show_template_init'] = $tmpData["is_init"];
  88. $data['show_template_default'] = $tmpData["is_default"];
  89. }
  90. return app('json')->success($data);
  91. }
  92. /**
  93. * 获取用户子级列表
  94. * @param Request $request
  95. */
  96. public function getChildList(Request $request){
  97. $post = UtilService::getMore([
  98. ['page', 1],
  99. ['pageSize', 50],
  100. ], $request);
  101. $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
  102. $post["page"] = $post["page"]<=0 ? 1 : (int)$post["page"];
  103. $post["parent_uid"]= $request->user["uid"];
  104. $data = (new UserModel)->getDataList($post,"u.uid,u.mobile,u.nickname,u.avatar");
  105. return app('json')->success($data);
  106. }
  107. /**
  108. * 获取用户总邀请人数排行榜
  109. * @param Request $request
  110. */
  111. public function getInviterRanking(Request $request)
  112. {
  113. $time = $request->param('time', time());
  114. $times = explode(" - ",$time);
  115. $page = $request->param('page', 1); // 获取请求中的页码参数,默认为 1
  116. $pageSize = $request->param('pageSize', 6); // 获取请求中的每页记录数参数,默认为 6
  117. if(sizeof($times)==2)
  118. {
  119. $count = (new UserModel) -> where('parent_uid', $request->user['uid'])->where('regtime','>=',$times[0])->where('regtime','<',$times[1])->count();
  120. }
  121. else
  122. {
  123. $count = (new UserModel) -> where('parent_uid', $request->user['uid'])->count();
  124. }
  125. $uids = (new UserModel) -> where('parent_uid', $request->user['uid'])
  126. -> column('uid');
  127. $list = [];
  128. if ($count == 0) {
  129. $list = (new UserModel)
  130. -> where('uid', '<>', $request->user['uid'])
  131. -> orderRaw('RAND()')
  132. -> limit(6)
  133. -> field('uid, nickname, avatar')
  134. -> select()
  135. -> toArray();
  136. foreach ($list as &$v) {
  137. $v['count'] = (new UserModel)->where('parent_uid', $v['uid'])->count();
  138. $v['auth_info'] = null;
  139. }
  140. } else {
  141. $list = (new UserModel)
  142. ->where('parent_uid', 'in', $uids)
  143. ->join('info_audit', 'user.uid = info_audit.uid', 'LEFT')
  144. ->group('parent_uid')
  145. ->field('parent_uid AS uid, COUNT(*) AS count, info_audit.user_work_type_id, info_audit.ancestral_place, info_audit.status')
  146. ->order('count', 'DESC')
  147. ->page($page, $pageSize)
  148. ->select()
  149. ->toArray();
  150. foreach ($list as &$v) {
  151. $user = (new UserModel)->where('uid', $v['uid'])->field('nickname, avatar')->find();
  152. $v['nickname'] = $user['nickname'];
  153. $v['avatar'] = $user['avatar'];
  154. $v['auth_info'] = [
  155. 'user_work_type_id' => $v['user_work_type_id'],
  156. 'ancestral_place' => $v['ancestral_place'],
  157. 'status' => $v['status'],
  158. ];
  159. }
  160. }
  161. return app('json')->success(compact('count','list'));
  162. }
  163. /**
  164. * 设置用户信息
  165. * @param Request $request
  166. */
  167. public function setUserInfo(Request $request){
  168. $post = UtilService::getMore([
  169. ['avatar',''],
  170. ['nickname',''],
  171. ['name',''],
  172. // ['mobile',''],
  173. ['sex', ''],
  174. ],$request);
  175. $save=[];
  176. if(!empty($post["avatar"])){
  177. $save["avatar"] = $post["avatar"];
  178. }
  179. if(!empty($post["nickname"])){
  180. $save["nickname"] = $post["nickname"];
  181. }
  182. if(!empty($post["name"])){
  183. $save["name"] = $post["name"];
  184. }
  185. // if(!empty($post["mobile"])){
  186. // if(is_mobile($post["mobile"])){
  187. // return app("json")->fail("请输入正确的手机号码");
  188. // }
  189. // $save["mobile"] = $post["mobile"];
  190. // }
  191. if(in_array((string)$post["sex"],["0","1","2"])){
  192. $save["sex"] = (int)$post["sex"];
  193. }
  194. if(empty($save)){
  195. return app("json")->fail("提交数据为空");
  196. }
  197. //是否需要审核
  198. $isInfoAudit = 0;
  199. if($isInfoAudit==0){
  200. $r = (new UserModel)->where("uid",$request->user["uid"])->update($save);
  201. if(!$r){
  202. return app("json")->fail("提交数据为空");
  203. }
  204. }else{
  205. $data = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  206. if(!empty($data) && $data["status"]==0){
  207. return app('json')->fail("资料审核中,请勿重复提交");
  208. }
  209. $save["uid"] = $request->user["uid"];
  210. $save["status"] = 0;
  211. $r = (new UserAudit)->insert($save);
  212. if(!$r){
  213. return app("json")->fail("提交数据为空");
  214. }
  215. }
  216. return app("json")->success("提交成功");
  217. }
  218. /**
  219. * 绑定手机号
  220. * @param Request $request
  221. */
  222. public function bindMobile(Request $request){
  223. [$code] = UtilService::getMore([
  224. ['code', '', 'empty', 'code参数错误'],
  225. ], $request, true);
  226. if(!empty($request->user['mobile'])){
  227. return app('json')->fail("当前账户已绑定过手机号码");
  228. }
  229. $weixinA = new weixina();
  230. $data=$weixinA->getPhoneNumber($code);//新版
  231. if(empty($data) || empty($data['purePhoneNumber'])) {
  232. return app('json')->fail("绑定失败,请重新绑定01".$weixinA->error);
  233. }
  234. $save=[
  235. // "countryCode"=>empty($data['countryCode'])?"":$data['countryCode'],
  236. "mobile"=>$data['purePhoneNumber'],
  237. ];
  238. // if($request->user["nickname"]=="微信用户"){
  239. // $save["nickname"] = $data['purePhoneNumber'];
  240. // }
  241. $r = (new UserModel)->where('uid', $request->user['uid'])->update($save);
  242. if(!$r){
  243. return app('json')->fail("绑定失败,请重新绑定02");
  244. }
  245. $result = [];
  246. $result['nickname'] = $request->user['nickname'];
  247. $result['avatar'] = $request->user['avatar'];
  248. return app('json')->success($result);
  249. }
  250. /**
  251. * 获取名片信息
  252. * @param Request $request
  253. */
  254. public function getUserCardInfo(Request $request){
  255. $data = (new InfoAudit)->getItem(["uid"=>$request->user["uid"],"status"=>1]);
  256. if(empty($data)){
  257. return app('json')->fail("您还没有通过名片信息审核");
  258. }
  259. $typeData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id","desc")->find();
  260. $data["is_type_audit"] = (empty($typeData) || $typeData["status"]!=1)?0:1;
  261. return app('json')->success($data);
  262. }
  263. /**
  264. * 提交资料审核
  265. * @param Request $request
  266. */
  267. public function subInfoAudit(Request $request){
  268. $data = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  269. if(!empty($data) && $data["status"]==0){
  270. return app('json')->fail("资料审核中,请勿重复提交");
  271. }
  272. $post = UtilService::getMore([
  273. ['avatar',''],
  274. ['name','','empty','请输入真实姓名'],
  275. ['mobile','','is_moblie','请输入正确的手机号码'],
  276. ['idcard','','empty','请输入正确的身份证号码'],
  277. ['birthday',''],
  278. ['service_type',''],
  279. ['service_price',''],
  280. ['service_min_price',''],
  281. ['service_max_price',''],
  282. ['service_area',[]],
  283. ['service_project',[]],
  284. ['service_intro_content',''],
  285. ['service_intro_imgs',[]],
  286. ['service_audit_imgs',[]],//此处为我的证书
  287. ['service_imgs',[]],//我的服务照片
  288. ['service_count',0],
  289. ['work_year',''],
  290. ['ancestral_place',''],
  291. ['education',''],
  292. ['minority',''],
  293. ['is_china',1],
  294. ['user_work_type_id','0'],//服务职称
  295. ['service_label',[]],//服务标签
  296. ],$request);
  297. if(!IdentityCard::isValid($post["idcard"])){
  298. return app('json')->fail("请输入正确的身份证号码");
  299. }
  300. $save=[];
  301. $save["avatar"] = empty($post["avatar"]) ? "" : $post["avatar"];
  302. $save["name"] = empty($post["name"]) ? "" : $post["name"];
  303. $save["mobile"] = empty($post["mobile"]) ? "" : $post["mobile"];
  304. $save["idcard"] = empty($post["idcard"]) ? "" : $post["idcard"];
  305. $save["service_count"] = $post['service_count'];
  306. // $save["birthday"] = empty($post["birthday"])? 0 : strtotime($post["birthday"]);
  307. $save["constellation"] = IdentityCard::get_starsign($post["idcard"]);//星座
  308. $save["twelve"] = IdentityCard::get_zodiac($post["idcard"]);//星座
  309. $save["birthday"] = strtotime(IdentityCard::get_birthday($post["idcard"]));
  310. //服务类型
  311. if(!empty($post["service_type"])){
  312. $timeTypeData = (new ServiceTimeType)->where("code",$post["service_type"])->where("status",1)->select();
  313. if(empty($timeTypeData)){
  314. return app('json')->fail("服务时长类型不存在");
  315. }
  316. $save["service_type"] = $post["service_type"];
  317. }
  318. //服务价格区间
  319. // $save["service_price"] = empty($post["service_price"]) ? "" : $post["service_price"];
  320. $save["service_min_price"] = empty($post["service_min_price"]) ? 0 : $post["service_min_price"];
  321. $save["service_max_price"] = empty($post["service_max_price"]) ? 0 : $post["service_max_price"];
  322. //服务区域
  323. $cityModel = new CityModel();
  324. if(!empty($post["service_area"]) && is_array($post["service_area"])){
  325. $saveAre=[];
  326. foreach($post["service_area"] as $v){
  327. $stc = str_replace(['省','市','区','县'],['','','',''],$v);
  328. $str = str_replace(['辖'],['市辖'],$stc);
  329. $arr = explode(",",$str);
  330. $city_id = $cityModel->where('merger_name','like',"%".$arr[1].",".$arr[2])->value('id');
  331. if(!$city_id) $city_id = $cityModel->where('merger_name','like',"%".$arr[0].",".$arr[1])->value('id');
  332. $saveAre[] = $city_id;
  333. }
  334. if(!empty($saveAre)){
  335. $save["service_area"] = implode(",", $saveAre);
  336. }
  337. }
  338. // //服务区域
  339. // $cityModel = new CityModel();
  340. // if(!empty($post["service_area"]) && is_array($post["service_area"])){
  341. // $saveAre=[];
  342. // foreach($post["service_area"] as $v){
  343. // @file_put_contents('dub.txt','1');
  344. // $arr = explode(",",$v);
  345. // $str1 = $arr[0].','.$arr[1];
  346. // @file_put_contents('dub.txt','2');
  347. // $stc = str_replace(['省','市','区','县'],['','','',''],$str1);
  348. // $str2 = $stc.",".$arr[2]!='市辖区'?str_replace(['省','市','区','县'],['','','',''],$arr[2]):'市辖区';
  349. // $arr3 = explode(",",$str2);
  350. // $city_id = $cityModel->where('merger_name','like',"%".$arr3[1].",".$arr3[2])->value('id');
  351. // @file_put_contents('dub.txt','3');
  352. // if(!$city_id)
  353. // {
  354. // $city_id = $cityModel->where('merger_name','like',"%".$arr3[0].",".$arr3[1])->value('id');
  355. // $city_id1 = $cityModel->where('merger_name','like',"%".$arr3[0].",".$arr3[1])->value('city_id');
  356. // $city_id2 = $cityModel->where('parent_id',$city_id1)->where('name','市辖区')->value('id');
  357. // if($city_id2>0) $city_id= $city_id2;
  358. // }
  359. // @file_put_contents('dub.txt','4');
  360. // $saveAre[] = $city_id;
  361. //
  362. // }
  363. // if(!empty($saveAre)){
  364. // $save["service_area"] = implode(",", $saveAre);
  365. // }
  366. // }
  367. //服务内容
  368. $serviceTypeModel = new ServiceTypeModel();
  369. if(!empty($post["service_project"]) && is_array($post["service_project"])){
  370. $saveCon=[];
  371. foreach($post["service_project"] as $k=>$v){
  372. if(empty(trim($v))){
  373. continue;
  374. }
  375. $itemData = $serviceTypeModel->where("id",(int)$v)->where("status",1)->find();
  376. if(!empty($itemData)){
  377. $saveCon[]=$itemData["id"];
  378. }
  379. }
  380. if(!empty($saveCon)){
  381. $save["service_project"] = implode(",", $saveCon);
  382. }
  383. }
  384. //服务标签
  385. $save["service_label"]="";
  386. $labelData = (new ServiceLabelModel)->getColumnList("id","id",$post["service_label"]);
  387. if(!empty($labelData)){
  388. $save["service_label"] = implode(",", $labelData);
  389. }
  390. $save["service_intro_content"] = empty($post["service_intro_content"])? "" : $post["service_intro_content"];
  391. $save["service_intro_imgs"] = empty($post["service_intro_imgs"]) ? "" : implode(",", $post["service_intro_imgs"]);
  392. $save["service_audit_imgs"] = empty($post["service_audit_imgs"]) ? "" : implode(",", $post["service_audit_imgs"]);
  393. $save["service_imgs"] = empty($post["service_imgs"]) ? "" : implode(",", $post["service_imgs"]);//我的服务展示
  394. $save['work_year'] = empty($post["work_year"]) ? "": $post["work_year"];
  395. $save['ancestral_place'] = empty($post["ancestral_place"])? "": $post["ancestral_place"];
  396. $save['education'] = empty($post["education"]) ? "": $post["education"];
  397. $save['minority'] = empty($post["minority"]) ? "": $post["minority"];
  398. $save["status"] = 0;
  399. $save["time"] = time();
  400. $save["uid"] = $request->user["uid"];
  401. $save['is_china'] = $post["is_china"];
  402. //服务职称
  403. $save["user_work_type_id"] = empty($post["user_work_type_id"]) ? 0: (int)$post["user_work_type_id"];
  404. if($save["user_work_type_id"]>0 && (new UserWorkType)->where("id",$post["user_work_type_id"])->where("status",1)->count()<=0){
  405. return app('json')->fail("当前类型不能选择");
  406. }
  407. //生成编码
  408. $r = (new InfoAudit)->insertGetId($save);
  409. if (!$r) {
  410. return app('json')->fail("系统错误");
  411. }
  412. $exist = (new InfoAudit)->where('uid', $save['uid'])->find();
  413. if ($exist && !empty($exist['no'])) {
  414. $no = $exist['no'];
  415. } else {
  416. $id = str_pad($r, 5, "0", STR_PAD_LEFT);
  417. $no = "MYJ" . date("ym") . $id;
  418. }
  419. (new InfoAudit)->where("id", $r)->update(["no" => $no]);
  420. return app('json')->success("提交成功,请耐心等待审核");
  421. }
  422. /**
  423. * 平台认证
  424. * @param Request $request
  425. */
  426. public function subTypeAudit(Request $request){
  427. $data = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  428. if(!empty($data) && $data["status"]==0){
  429. return app('json')->fail("平台审核中,请勿重复提交");
  430. }
  431. $post = UtilService::getMore([
  432. ['service_audit_imgs',[],"empty","请上传服务认证截图"],
  433. ],$request);
  434. $save=[];
  435. $save["service_audit_imgs"] = empty($post["service_audit_imgs"]) ?"": implode(",", $post["service_audit_imgs"]);
  436. $save["status"] = 0;
  437. $save["time"] = time();
  438. $save["uid"] = $request->user["uid"];
  439. if(empty($save["service_audit_imgs"])){
  440. return app('json')->fail("请上传服务认证截图");
  441. }
  442. $r = (new TypeAudit)->insertGetId($save);
  443. if(!$r){
  444. return app('json')->fail("系统错误");
  445. }
  446. $no = "CERT-".date("YmdHis")."-".$r;
  447. (new TypeAudit)->where("id",$r)->update(["no"=>$no]);
  448. return app('json')->success("提交成功,请耐心等待审核");
  449. }
  450. /**
  451. * 模板订单提交[第一步]
  452. * @param Request $request
  453. */
  454. public function subShowTemplateOrder(Request $request){
  455. [$id,$pay_type] = UtilService::getMore([
  456. ['id','','empty','参数错误'],
  457. ['pay_type','','empty','请选择支付方式'],
  458. ],$request,true);
  459. if(!in_array($pay_type,["wxpay","balance"])){
  460. return app('json')->fail('不支持该支付方式!');
  461. }
  462. $weixinConfig = (new SysModel)->getWeixinConfig();
  463. // if(empty($weixinConfig)){
  464. // return app('json')->fail('支付配置为空!');
  465. // }
  466. //缓存
  467. $redis = \think\facade\Cache::store('redis');
  468. $key = 'show_template_order_sub_' . $request->user['uid'];
  469. $bool = $redis->handler()->exists($key);
  470. if ($bool) {
  471. return app('json')->fail('请务重复操作,请稍等在重试!');
  472. }
  473. $redis->set($key,1,5);//5秒缓存
  474. $proData = (new ShowTemplate)->where("id",$id)->where("status",1)->find();
  475. if(empty($proData)){
  476. return app('json')->fail("当前模板已下架");
  477. }
  478. $proData = $proData->toArray();
  479. $count = (new UserShowTemplate)->where("uid",$request->user['uid'])->where("show_template_id",$id)->count();
  480. if($count>0){
  481. return app('json')->fail("您已购买过当前模板");
  482. }
  483. //验证
  484. $orderCount = (new ShowTemplateOrder)->where("uid",$request->user['uid'])->where("show_template_id",$id)->where("status",1)->count();
  485. if($orderCount>0){
  486. return app('json')->fail("您已下单该模板,请勿重复下单");
  487. }
  488. $price = floatval($proData["price"]);
  489. // if($price<0.01){
  490. // return app('json')->fail("模板信息错误");
  491. // }
  492. $allMoney = $price;//订单商品费用
  493. $total_money = $allMoney;//订单总费用
  494. $payMoney = $total_money;//订单需支付费用
  495. $payMoney = $payMoney <= 0 ? 0 : $payMoney;
  496. $nowTime = time();
  497. //余额支付验证
  498. if($pay_type=="balance" && $payMoney > $request->user["money"]){
  499. return app('json')->fail("当前余额不足");
  500. }
  501. //主订单数据
  502. $save=[];
  503. $save['uid'] = $request->user['uid'];
  504. $save['order_id'] = makeOrderId($request->user['uid'],"ST");
  505. $save['pay_type'] = $pay_type;//
  506. $save['total_money'] = $total_money;//订单总金额
  507. $save['all_money'] = $allMoney;//商品中金额
  508. $save['pay_money'] = $payMoney;//实际支付金额
  509. $save['balance'] = 0;//余额支付了多少(目前不用)
  510. $save['status'] = $payMoney <= 0 ? 1 : 0;
  511. $save['pay_time'] = $payMoney <= 0 ? time() : 0;
  512. $save['time'] = $nowTime;
  513. $save['show_template_id'] = $proData["id"];
  514. $save['show_template_title'] = $proData["title"];;
  515. $save['show_template_price'] = $proData["price"];
  516. $save['show_template_img'] = empty($proData["imgs"]) ? "" : explode(",", $proData["imgs"])[0];
  517. $save['show_template_code'] = $proData["code"];
  518. //余额实时支付
  519. if($pay_type=="balance"){
  520. $save['status'] = 1;
  521. $save['pay_time'] = time();
  522. }
  523. try{
  524. Db::startTrans();
  525. $o_id = (new ShowTemplateOrder)->insertGetId($save);
  526. if(empty($o_id)){
  527. return app('json')->fail("订单提交失败");
  528. }
  529. //不需要支付
  530. if($payMoney<=0 && $save['status']==1){
  531. //验证并绑定当前模板
  532. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  533. Db::commit();
  534. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  535. }
  536. //余额支付
  537. if($pay_type=="balance"){
  538. //验证并绑定当前模板
  539. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  540. //修改用户余额
  541. $res = (new UserDetailModel)->balancePay($request->user["uid"],$payMoney,"show_temp_pay",["to_id"=>$o_id]);
  542. if(!$res){
  543. Db::rollback();
  544. return app('json')->fail("余额支付失败");
  545. }
  546. Db::commit();
  547. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  548. }
  549. //微信支付
  550. if(empty($request->user['openid'])){
  551. Db::rollback();
  552. return app('json')->fail('用户还未绑定微信!');
  553. }
  554. //清理之前支付凭证 || 防止重复购买
  555. $payTrade = (new PayTradeModel)
  556. ->where("uid",$request->user["uid"])
  557. ->where("o_id",$o_id)
  558. ->where("type","temp")
  559. ->where("status",0)
  560. ->where("time","<",time() - 7*24*60*60)
  561. ->select()
  562. ->toArray();
  563. $wxpay = new wxpayApi();
  564. // $wxpay = new wxpayApi($weixinConfig);
  565. foreach ($payTrade as $v) {
  566. // if($v['pay_type'] == 'wxpay') {
  567. // $result = $wxpay->closeOrder($v['pay_no']);
  568. // }
  569. (new PayTradeModel)->where("id",$v['id'])->where("status",0)->delete();
  570. }
  571. $mtime = microtime(true)*10000;
  572. $payOn = "T".date("Ymd").$mtime .rand(100,999) . $request->user['uid'];
  573. $out_trade_no="";
  574. $payType = $save["pay_type"];
  575. //添加交易记录
  576. $trade = [
  577. 'uid' => $request->user['uid'],
  578. 'o_id' => $o_id,
  579. 'order_id' =>$save["order_id"],
  580. 'pay_no' => $payOn,
  581. 'out_trade_no' => empty($out_trade_no) ? $payOn : $out_trade_no,
  582. 'pay_type' => $payType,
  583. 'money' => $payMoney,
  584. 'type' => 'temp',
  585. 'd_json' => serialize(['orderId'=>$save["order_id"],"give_score"=>0]),
  586. 'time' => time(),
  587. 'status' => 0,
  588. ];
  589. $r=(new PayTradeModel)->insert($trade);
  590. if(!$r){
  591. Db::rollback();
  592. return app('json')->fail('支付信息获取失败!');
  593. }
  594. $clictip = get_client_ip();
  595. if(empty($clictip)){
  596. $clictip = $request->ip();
  597. }
  598. $payData = $wxpay->wxmpPay([
  599. 'body' => "微信小程序购买模板",
  600. 'out_trade_no' => $payOn,
  601. 'total' => $payMoney,
  602. 'openid' => $request->user['openid'],
  603. 'payer_client_ip' => $clictip,
  604. ]);
  605. if(empty($payData)){
  606. Db::rollback();
  607. return app('json')->fail($wxpay->errorMsg);
  608. }
  609. Db::commit();
  610. $redis->delete($key);
  611. return app('json')->success([
  612. 'jsApiParameters'=> $payData,
  613. 'pay_no' => $payOn,
  614. 'order_id' => $save["order_id"],
  615. "status" => $save['status'],
  616. "money" => $payMoney,
  617. ]);
  618. } catch (DbException $db){
  619. Db::rollback();
  620. return app('json')->fail("订单生成失败");
  621. }
  622. }
  623. /**
  624. * 获取模板购买订单详情
  625. * @param Request $request
  626. */
  627. public function payShowTemplateOrderInfo(Request $request){
  628. [$order_id] = UtilService::getMore([
  629. ['order_id','','empty','参数错误'],
  630. ],$request,true);
  631. $data = (new ShowTemplateOrder)
  632. ->field("order_id,total_money,all_money,pay_money,status,time")
  633. ->where("order_id",$order_id)
  634. ->where("uid",$request->user["uid"])
  635. ->find();
  636. if(empty($data)){
  637. return app('json')->fail('信息不存在!');
  638. }
  639. $data=$data->toArray();
  640. if($data["status"]==0 && $data["time"]<time() - 30*60){
  641. (new ShowTemplateOrder)->where("id",$data["id"])->where("uid",$request->user["uid"])->update(["status"=>-1]);
  642. $data["status"]==-1;
  643. }
  644. $data["time"] = date("Y-m-d H:i:s",$data["time"]);
  645. return app('json')->success($data);
  646. }
  647. /**
  648. * 用户模板列表
  649. * @param Request $request
  650. */
  651. public function userShowTemplateList(Request $request){
  652. $post = UtilService::getMore([
  653. ['page', 1],
  654. ['pageSize', 50],
  655. ], $request);
  656. $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
  657. $post["page"] = $post["page"]<=0 ? 1 : (int)$post["page"];
  658. $where=[];
  659. $where[]=["ut.uid","=",$request->user["uid"]];
  660. $totalCount = (new UserShowTemplate)->alias("ut")->where($where)->count();
  661. $data=null;
  662. if($totalCount>0){
  663. $data = (new UserShowTemplate)
  664. ->field("ut.id,t.id as show_template_id,t.title,t.price,t.old_price,t.status,t.imgs,t.is_hot,t.is_recommend,t.code,look_count,t.real_sales,t.unreal_sales,ut.is_default")
  665. ->alias("ut")
  666. ->join("show_template t", "t.id = ut.show_template_id","left")
  667. ->where($where)
  668. ->order("ut.is_default", "desc")
  669. ->order("ut.id", "desc")
  670. ->page($post["page"], $post["pageSize"])
  671. ->select();
  672. foreach($data as $k=>$v){
  673. $data[$k]["is_use"] = 1;//是否已经购买或者可以使用
  674. $data[$k]["imgs"] = getImageAr($v["imgs"]);
  675. $data[$k]["img"] = empty($data[$k]["imgs"]) ? "" : $data[$k]["imgs"][0];
  676. $data[$k]["sales_count"] = $data[$k]["real_sales"] + $data[$k]["unreal_sales"];
  677. unset($data[$k]["real_sales"]);
  678. unset($data[$k]["unreal_sales"]);
  679. }
  680. }
  681. $data = empty($data)?[]:$data;
  682. return app('json')->success(["list" => $data, "pageSize" => $post["pageSize"],"page"=>$post["page"],"totalCount"=>$totalCount]);
  683. }
  684. /**
  685. * 设置默认模板
  686. * @param Request $request
  687. */
  688. public function setShowTemplate(Request $request) {
  689. [$show_template_id] = UtilService::getMore([
  690. ['show_template_id', '', 'empty', '参数错误'],
  691. ], $request, true);
  692. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("is_default", 1)->update(["is_default" => 0]);
  693. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("show_template_id", $show_template_id)->update(["is_default" => 1]);
  694. return app('json')->success("设置成功");
  695. }
  696. /**
  697. * 获取邀请海报小程序码
  698. * @param Request $request
  699. */
  700. public function getWxmpInviteQrcode(Request $request){
  701. $inviteData = (new SysModel)->getDataInfo("invite");
  702. $bgimg = $inviteData["img"];
  703. if(!empty($request->user["invite_img"])){
  704. return app('json')->success(["qrcode"=>$request->user["invite_img"],"bgimg"=>$bgimg]);
  705. }
  706. $weixinA = new weixina();
  707. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  708. $data = $weixinA->getUnlimitedQRCode("pages/index/index",$request->user["uid"]);
  709. // var_dump($data);
  710. if(empty($data)){
  711. return app('json')->fail("小程序码获取失败".$weixinA->error);
  712. }
  713. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  714. $res = $this->uploadImageBase64("wximg",$base64,1);
  715. if($res["code"]!=1){
  716. return app('json')->fail($res["msg"]);
  717. }
  718. (new UserModel)->where("uid",$request->user["uid"])->update(["invite_img"=>$res["url"]]);
  719. return app('json')->success(["qrcode"=>$res["url"],"bgimg"=>$bgimg]);
  720. }
  721. // public function getWxmpInviteQrcode2(Request $request){
  722. //
  723. // //获取小程序码
  724. // $weixinA = new weixina();
  725. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  726. // if(empty($data)){
  727. // return app('json')->fail("小程序码获取失败".$weixinA->error);
  728. // }
  729. // $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  730. // $code = "temp";
  731. // $sysData = (new SysModel())->where("id",1)->find();
  732. // $uploadConfig = config('filesystem');
  733. // //验证base64格式
  734. // preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  735. // if(!$result){
  736. // return ["code"=>-1,"msg"=>"base64格式格式错误"];
  737. // }
  738. // //验证图片后缀
  739. // if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  740. // return ["code"=>-1,"msg"=>"不支持的图片格式"];
  741. // }
  742. // $rootPath = config('filesystem.disks.resource.root');
  743. // $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  744. // $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  745. // $path = dirname($filePath);
  746. // // 检测目录
  747. // if (!is_dir($path)) {
  748. // if (!mkdir($path, 0777, true)) {
  749. // return ["code"=>-1,"msg"=>"生成目录失败"];
  750. // }
  751. // return ["code"=>-1,"msg"=>"上传目录不存在"];
  752. // }
  753. // //重名文件验证
  754. // if (is_file($filePath)) {
  755. // return ["code"=>-1,"msg"=>"文件已存在"];
  756. // }
  757. // if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  758. // return ["code"=>-1,"msg"=>"文件报错失败"];
  759. // }
  760. //
  761. // //获取海报背景
  762. // $inviteData = (new SysModel)->getDataInfo("invite");
  763. // if(empty($inviteData["img"])){
  764. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  765. // }
  766. // $bgimg =explode("resource", $inviteData["img"])[1];
  767. // if(empty($bgimg)){
  768. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  769. // }
  770. //
  771. // $savePath = $rootPath. DIRECTORY_SEPARATOR .$code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true))."b".".jpg";
  772. //
  773. //
  774. //
  775. //
  776. // $bg = $rootPath.$bgimg;
  777. // $bgSize = getimagesize($bg);
  778. // $qrcodeSize = getimagesize($filePath);
  779. // $handle = Image::open($bg);
  780. // $handle->water($filePath,[($bgSize[0]-$qrcodeSize[0])/2,($bgSize[1]-$qrcodeSize[1])/2]);
  781. // $handle->save($savePath,"jpg",80);
  782. // $qiniu = new Qiniu;
  783. // $img_url = $qiniu->updateFile('img', $savePath, $savePath);
  784. // if (empty($img_url['url'])) {
  785. // return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  786. // }
  787. // @unlink($filePath);
  788. // @unlink($savePath);
  789. // return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  790. // }
  791. //
  792. // public function checkImgPath(){
  793. //
  794. // }
  795. /**
  796. * 图片合成
  797. * @param type $bg
  798. * @param type $qrcode
  799. * @param type $savePath
  800. */
  801. public function createPosterImg($bg,$qrcode,$savePath){
  802. }
  803. /**
  804. * 获取小程序码
  805. * @param Request $request
  806. */
  807. public function getWxmpQrcode(Request $request){
  808. $weixinA = new weixina();
  809. $data = $weixinA->getUnlimitedQRCode("pages/index/index","a=1");
  810. if(empty($data)){
  811. return app('json')->fail("小程序码获取失败".$weixinA->error);
  812. }
  813. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  814. $res = $this->uploadImageBase64("wximg",$base64);
  815. if($res["code"]!=1){
  816. return app('json')->fail($res["msg"]);
  817. }
  818. return app('json')->success(["img"=>$res["data"]]);
  819. }
  820. /**
  821. *
  822. * @param Request $request
  823. */
  824. public function uploadBase64(Request $request){
  825. [$img,$code] = UtilService::getMore([
  826. ['img', '','empty',"请上传图片"],
  827. ['code', 'image'],
  828. ], $request,true);
  829. // $imgAr = explode("base64,",$img);
  830. // if(empty($imgAr)){
  831. // return app("json")->fail("请上传base64图片");
  832. // }
  833. // $imgBase64 = count($imgAr)==1?$imgAr[0]:$imgAr[1];
  834. // //判断字符串是否经过编码方法
  835. // if($imgBase64!=base64_encode(base64_decode($imgBase64))){
  836. // return app("json")->fail("请上传base64图片");
  837. // }
  838. // $base64 = "data:application/octet-stream;base64,".$imgBase64;//七牛
  839. $res = $this->uploadImageBase64($code,$img);
  840. if($res["code"]!=1){
  841. return app('json')->fail($res["msg"]);
  842. }
  843. return app('json')->success(["img"=>$res["data"]]);
  844. }
  845. /**
  846. * 图片上传
  847. * @param Request $request
  848. * @return type
  849. */
  850. public function upload(Request $request){
  851. $uploadConfig = config('filesystem');
  852. $sysData = (new SysModel())->where("id",1)->find();
  853. $file = $request->file('file');
  854. $code = $request->post("code","image");
  855. if(empty($file)) {
  856. return app('json')->fail("未上传文件");
  857. }
  858. $size = $file->getSize();
  859. if(!empty($size) && $size>$uploadConfig["image"]["size"]*1024*1024){
  860. return app('json')->fail("图片不能超过{$uploadConfig["image"]["size"]}M");
  861. }
  862. if(!in_array($code, $uploadConfig['image']['path'])){
  863. return app('json')->fail("上传路径错误");
  864. }
  865. $ext = $file->extension();
  866. if(!in_array($ext, $uploadConfig['image']['ext'])){
  867. return app('json')->fail("图片类型错误");
  868. }
  869. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  870. if(!$upPath){
  871. return app('json')->fail("上传失败01");
  872. }
  873. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  874. $imgUrl = str_replace("\\", "/", $savePath);
  875. return app('json')->success(['img'=>$imgUrl,'size'=>$size]);
  876. }
  877. /**
  878. * 视频上传
  879. * @param Request $request
  880. * @return type
  881. */
  882. public function uploadVideo(Request $request){
  883. $uploadConfig = config('filesystem');
  884. $sysData = (new SysModel())->where("id",1)->find();
  885. $file = $request->file('file');
  886. $code = $request->post("code","video");
  887. if(empty($file)) {
  888. return app('json')->fail("未上传文件");
  889. }
  890. if(!in_array($code, $uploadConfig['video']['path'])){
  891. return app('json')->fail("上传路径错误");
  892. }
  893. $ext = $file->extension();
  894. if(!in_array($ext, $uploadConfig['video']['ext'])){
  895. return app('json')->fail("视频类型错误");
  896. }
  897. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  898. if(!$upPath){
  899. return app('json')->fail("上传失败01");
  900. }
  901. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  902. $imgUrl = str_replace("\\", "/", $savePath);
  903. return app('json')->success(['video'=>$imgUrl]);
  904. }
  905. /**
  906. * base64文件上传
  907. * @param type $code
  908. * @param type $base64
  909. */
  910. public function uploadImageBase64($code,$base64,$isQiniu=0){
  911. $sysData = (new SysModel())->where("id",1)->find();
  912. $uploadConfig = config('filesystem');
  913. //验证base64格式
  914. preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  915. if(!$result){
  916. return ["code"=>-1,"msg"=>"base64格式格式错误"];
  917. }
  918. //验证图片后缀
  919. if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  920. return ["code"=>-1,"msg"=>"不支持的图片格式"];
  921. }
  922. $rootPath = config('filesystem.disks.resource.root');
  923. $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  924. $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  925. $path = dirname($filePath);
  926. // 检测目录
  927. if (!is_dir($path)) {
  928. if (!mkdir($path, 0777, true)) {
  929. return ["code"=>-1,"msg"=>"生成目录失败"];
  930. }
  931. return ["code"=>-1,"msg"=>"上传目录不存在"];
  932. }
  933. //重名文件验证
  934. if (is_file($filePath)) {
  935. return ["code"=>-1,"msg"=>"文件已存在"];
  936. }
  937. if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  938. return ["code"=>-1,"msg"=>"文件报错失败"];
  939. }
  940. //七牛上传
  941. if($isQiniu==1){
  942. $qiniu = new Qiniu;
  943. $img_url = $qiniu->updateFile('img', $filePath, $filePath);
  944. if (empty($img_url['url'])) {
  945. return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  946. }
  947. @unlink($filePath);
  948. return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  949. }
  950. $savePath = $sysData['system_url'].config('filesystem.disks.resource.url').DIRECTORY_SEPARATOR.$hashName;
  951. return ["code"=>1,"url"=>str_replace("\\", "/", $savePath)];
  952. }
  953. /**
  954. * 七牛上传图片
  955. * @param Request $request
  956. */
  957. public function qiniuUpload(Request $request)
  958. {
  959. $file = $request->file('file');
  960. if (empty($file)) {
  961. return app('json')->fail("未上传文件");
  962. }
  963. $rootTmp = config('filesystem.disks.local.root') . '/' . \think\facade\Filesystem::putFile('tmp', $file);
  964. $image_size = @getimagesize($rootTmp);
  965. if ($image_size[0] > 1000) {
  966. $imgS = Image::open($rootTmp);
  967. $imgS->thumb(1000, $image_size[1]);
  968. $imgS->save($rootTmp);
  969. } else {
  970. if ($image_size[1] > 1000) {
  971. $imgS = Image::open($rootTmp);
  972. $imgS->thumb($image_size[0], 1000);
  973. $imgS->save($rootTmp);
  974. }
  975. }
  976. $qiniu = new Qiniu;
  977. $img_url = $qiniu->updateFile('img', $rootTmp, $rootTmp);
  978. if (empty($img_url['url'])) {
  979. return app('json')->fail($qiniu->getError());
  980. }
  981. @unlink($rootTmp);
  982. return app('json')->success(['img' => $img_url['url']]);
  983. }
  984. /**
  985. * 七牛上传token
  986. * @param Request $request
  987. */
  988. public function qiniuUploadToken(Request $request){
  989. [$bucket] = UtilService::getMore([
  990. ['bucket', ''],
  991. ], $request,true);
  992. $qiniu = new Qiniu;
  993. $token = $qiniu->createUploadToken($bucket);
  994. return app('json')->success(['token' => $token]);
  995. }
  996. /**
  997. * 获取用户总邀请人数
  998. * @param int $uid 用户ID
  999. * @return int 总邀请人数
  1000. */
  1001. public function getTotalInvites($uid)
  1002. {
  1003. return (new UserModel)->where('parent_uid', $uid)->count();
  1004. }
  1005. }