User.php 43 KB

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