User.php 42 KB

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