User.php 42 KB

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