User.php 43 KB

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