source = $this->request->header('source'); $this->merId = $this->request->header('merId'); } /** * 计算国盛小程序市场管理分红 */ public function gscm($mer_id=1){ // $enterprise=Db::name('enterprise')->where('type',1)->select(); $enterprise=Db::name('enterprise')->where('mer_id',$mer_id)->where('type',1)->find(); if(!$enterprise){ return false; } $reward[6]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',6)->column('uid'); $reward[5]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',5)->column('uid'); $reward[4]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',4)->column('uid'); $reward[3]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',3)->column('uid'); $reward[2]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',2)->column('uid'); $reward[1]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',1)->column('uid'); // $uids = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2],$reward[1]); $uids_money=[]; $enterprise_money=Db::name('enterprise_bill')->where('mer_id',$mer_id)->sum('money'); $amoney=$enterprise_money*0.05; $divvy=decimal2($amoney*0.3);//平均分红 $jiaquan_divvy=$amoney-$divvy;//加权分红 //平均分红金额不足每人0.01 就不分了 if($divvy > 0 || decimal2($divvy/(count($reward[6])*6+count($reward[5])*5+count($reward[4])*4+count($reward[3])*3+count($reward[2])*2+count($reward[1]))) > 0 ){ //0-普通用户 1-微店 2-云店 3-旗舰店 4-消费合伙人 5-创业合伙人 6-股东合伙人 for ($i=6;$i>0;$i--) { if ($i == 6) { $mergedArray = $reward[6]; }elseif($i==5){ $mergedArray = array_merge($reward[6],$reward[5]); }elseif($i==4){ $mergedArray = array_merge($reward[6],$reward[5],$reward[4]); }elseif($i==3){ $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3]); }elseif($i==2){ $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2]); }else{ $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2],$reward[1]); } $fenhong=decimal2($divvy/count($mergedArray)); foreach ($mergedArray as $v){ if(!isset($uids_money[$v])){ $uids_money[$v]=$fenhong; }else{ $uids_money[$v]+=$fenhong; } } } dump($uids_money); } } function jisuantuandui($where,$data=[]){ $enterprise_user_team=DB::name('enterprise_user')->where($where)->column('uid'); $arr=array_merge($data,$enterprise_user_team); foreach ($enterprise_user_team as $v){ $where['node_uid']=$v; $arr=$this->jisuantuandui($where,$arr); } return $arr; } public function importExcel() { $file = request()->file('file'); // 创建一个新的Excel读取器对象 $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($file); // 选择活动工作表 $objPHPExcel->setActiveSheetIndex(0); $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); // 循环遍历行和列 $yonghu=[]; foreach ($sheetData as $k=>$row) { if($k==1){ continue; } if($row['A'] && $row['A']!=NULL && $row['A']!=''){ $yonghu[]=array('a'=>$row['A'],'b'=>$row['B']); } } $repository = app()->make(UserRepository::class); foreach ($yonghu as $k=>$v){ $user = $repository->accountByUser($v['a']); if ($user){ // return app('json')->fail('手机号已存在'); $yonghu[$k]['user'] = $user; }else{ $yonghu[$k]['user'] = $repository->registr($v['a'],'A123456','APP',0); } } foreach ($yonghu as $v){ $user=$v['user']; if($v['b'] && $v['b']!=null && $v['b']!=''){ $pid=Db::name('user')->where('account',$v['b'])->value('uid'); if($pid){ $repository->bindSpread($user, intval($pid)); } } } } public function test() { $this->importExcel(); echo '导入成功'; die; $storeOrderRepository = app()->make(StoreOrderRepository::class); // $storeOrderRepository->yihuchashengji();//一壶茶身份升级 // $storeOrderRepository->yunyingjiangli();//运营中心奖励 // $storeOrderRepository->yihuchafenxiang();//一壶茶分红逻辑memberSettings // $this->jinjian();die; var_dump(11); die; $order_id = (int)$this->request->param('id'); $order=Db::name('store_order')->find($order_id); if(!$order){ return '订单不存在'; } //在rrx_store_order_product 表中查到product_id ,在rrx_store_product 查spu_id 在rrx_douhuomall表中查goods_id $out_order_no=$order['douhuomall_order_no']; $after_type='1';//1=未收货退款,2=退货退款,3=换货补发,4=不退货仅退款 $explain='测试退货'; $can_after_data=GongApiRequest::is_can_after( $out_order_no); dump($can_after_data); if(isset($can_after_data['result']['order_goods'])){ foreach ($can_after_data['result']['order_goods'] as $v){ $order_goods_id=$v['order_goods_id']; $after_num=$v['after_num']; $res=GongApiRequest::apply_after_sales( $order_goods_id,$out_order_no, $after_type, $explain, $after_num); dump($res); } } // // $storeGroupOrderRepository = app()->make(StoreGroupOrderRepository::class); // $res=$storeGroupOrderRepository->ProductOutCancel(6105); // $res = GongApiRequest::order_details('wx1698916402673749101'); $res2=GongApiRequest::after_status_new($out_order_no); dump($res2); // dump($repository->getBangFu(9640)); // dump($userRepository -> getCountUId(18)); // echo '开发者测试'; // echo systemConfig("pay_wx"); // $res = [ // "completeDateTime"=>"2022-05-31 14:27:09", // "remark"=>"1", // "orderAmount"=>"100", // "merchantId"=>"899104033", // "requestId"=>"wx1653980751822534740_5366", // "hmac"=>"yivznJKbCfPpnXpwsalGDz7tnRyjr9pqbeVSkVKZ5VvtnJqn4helUkGC+S2tsaF8oknwvN\/ZeoDcgtRPqT1uanOWyalSFip6qxkBDkbc\/sJBVMCR2vzp38+YEHbusuxH1O9D696bt\/PSuhFjItD9pFi+Qteha1zN8X4oxpWFEob4wOVcFnMHLkgehNoWy1NRqjz+RmD6osAzJrIS27RJmUaqt83e0ejcjfEzAEw74rq4Yafyx9PohjvF35iwVLCpOcdyxVsfuJ4D59ayqsgUs0\/80GMRvNkgXrO6bsN7m1t6PLSQgPkD6ruEX\/i4l4uhrpHLvnpc4wl9YsGS1k4SrQ==", // "clearingOrg"=>"UNION_PAY", // "totalRefundCount"=>"0", // "serialNumber"=>"ddd", // "realBankSerialNumber"=>"4200001429202205315964134213", // "orderCurrency"=>"CNY", // "realBankRequestNumber"=>"1531522625975881728N", // "totalRefundAmount"=>"0", // "paymentModeAlias"=>"MINIAPPS_WEIXIN_PAY", // "status"=>"SUCCESS" // ]; // $requestId = []; // if(strpos($res['requestId'],'_') !== false){ // $requestId = explode("_",$res['requestId']); // } // if($res['status'] == 'SUCCESS'){ // Db::name('store_group_order') -> where('group_order_sn',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber']]); // $pay_type = $res['paymentModeAlias'] == 'MINIAPPS_WEIXIN_PAY' ? 1 : 4; // event('pay_success_order', ['order_sn' => $requestId[0],'pay_type'=>$pay_type]); // } // Db::name('test') -> insert(['date'=>date('Y-m-d H:i:s')]); // try { // $merch_no = $this->request->param('merch_no'); // $mer_name = $this->request->param('mer_name'); // $mer_short_name = $this->request->param('mer_short_name'); // $response = $this->merchantModify(['merch_no' => $merch_no,'mer_name' => $mer_name, 'mer_short_name' => $mer_short_name,'agent_apply_no' => (string)time()]); // return app('json')->success($response); // } catch (\Throwable $e) { // return app('json')->fail($e->getMessage()); // } } //商户进件 private function jinjian(){ // $returndata=[ // 'request_id'=>time().rand(111111,999999), // 'usr_phone'=>'15732652759', // 'cont_name'=>'吴国珍', // 'cont_phone'=>'13911251783', // 'customer_email'=>'312009092@qq.com', // 'mer_name'=>'北京天地博爱科技有限公司', // 'mer_short_name'=>'天地博爱科技', // 'reg_addr'=>'北京市北京经济技术开发区科创十三街31号院二区14号楼9层901-3(北京自贸试验区高端产业片区亦庄组团)', // 'cust_addr'=>'北京市北京经济技术开发区科创十三街31号院二区14号楼9层901-3(北京自贸试验区高端产业片区亦庄组团)', // 'cust_tel'=>'010-53327000', // 'legal_name'=>'吴国珍', // 'legal_type'=>0, // 'legal_idno'=>'321123196710192020', // 'legal_mp'=>'13911251783', // 'legal_start_cert_id_expires'=>'20061129', // 'legal_id_expires'=>'20261129', // 'card_id_mask'=>'629966688', // 'card_name'=>'北京天地博爱科技有限公司', // 'bank_acct_type'=>'1', // 'bank_code'=>'03050000', // 'prov_code'=>'0011',//省份编码 (省市编码), // 'area_code'=>'1100',//地区编码 (省市编码) // 'license_code'=>'91110105697724649E', // 'mer_valid_date'=>'20291118', // 'mer_start_valid_date'=>'20091119', // 'entry_mer_type'=>'1', // 'rsa_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxTpMESsdhyjKQC+y1G++eXCEu5pXqK7fvkZJdubSTCQn/RM3soOMcCwTekULCxEUwM0SnPxFLcZuP/a8w87zWeAXoBCPJl1gVK4KZ+3tWq/BJPCET3Vy66M7pXfXL+ekd8gf2LWtEfpJoAn59guVfsbTOp44ppDkrb3SuXDcKhQIDAQAB' // ]; $returndata=[ 'request_id'=>time().rand(111111,999999), 'usr_phone'=>'13911251783',//注册手机号 'cont_name'=>'陈立军',//联系人姓名 'cont_phone'=>'13911251783',//联系人手机号码 'customer_email'=>'312009092@qq.com',//电子邮箱 'mer_name'=>'河北省一壶茶电子商务有限公司',//商户名称 'mer_short_name'=>'一壶茶电子商务',//商户简称 商户简称,长度为10个中文 'reg_addr'=>'河北省秦皇岛市经济技术开发区华山中路8号银通大厦',//注册地址 'cust_addr'=>'河北省秦皇岛市经济技术开发区华山中路8号银通大厦',//经营地址 'cust_tel'=>'010-53327000',//商户电话 'legal_name'=>'陈立军',//法人/负责人 姓名 'legal_type'=>0,//法人/负责人证件号码 'legal_idno'=>'130302196709281432',//法人/负责人证件号码 'legal_mp'=>'13911251783',//法人/负责人手机号 'legal_start_cert_id_expires'=>'20230310',//法人/负责人身份证有效期(始),格式 YYYYMMDD 'legal_id_expires'=>'20991231',//法人/负责人身份证有效期(至),格式 YYYYMMDD 'card_id_mask'=>'13050163560800002447',//结算银行卡号 'card_name'=>'河北省一壶茶电子商务有限公司',//结算银行卡开户姓名 'bank_acct_type'=>'1',//结算银行账户类型,1 : 对公, 2 : 对私。小微只能是对私 'bank_code'=>'01050000',//结算银行卡所属银行code 'prov_code'=>'0013',//结算银行卡省份编码, 'area_code'=>'1308',//结算银行卡省份编码 'license_code'=>'91130301MAD48PT00A',//营业执照编码 'mer_valid_date'=>'20991231',//商户有效日期(至),格式 YYYYMMDD(若为长期有效,固定为“20991231”;若开户企业类商户,必填) 'mer_start_valid_date'=>'20231107',//商户有效日期(至),格式 YYYYMMDD(若为长期有效,固定为“20991231”;若开户企业类商户,必填) 'entry_mer_type'=>'1',//商户类型:1-企业;2-小微。默认为企业 'rsa_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxTpMESsdhyjKQC+y1G++eXCEu5pXqK7fvkZJdubSTCQn/RM3soOMcCwTekULCxEUwM0SnPxFLcZuP/a8w87zWeAXoBCPJl1gVK4KZ+3tWq/BJPCET3Vy66M7pXfXL+ekd8gf2LWtEfpJoAn59guVfsbTOp44ppDkrb3SuXDcKhQIDAQAB' ]; dump($returndata); $arr= $this->incoming_parts($returndata,'config'); dump($arr);die; } /** * 业绩奖-服务中心分红-发放 * @return mixed */ public function yihuchafenxiang(){ $storeOrderRepository = app()->make(StoreOrderRepository::class); $storeOrderRepository->yihuchafenxiang(); $storeOrderRepository->yunyingjiangli(); return app('json')->success('业绩奖-服务中心分红-运营中心-发放完成'); } /** * 一壶茶身份升级 * @return mixed */ public function yihuchashengji(){ $storeOrderRepository = app()->make(StoreOrderRepository::class); $storeOrderRepository->yihuchashengji(); return app('json')->success('一壶茶身份升级-完成'); } public function shareImgesList(){ $where['mer_id']=$this->merId; $where['status']=0; $classify=$this->request->param('classify',0); if($classify){ $where['classify']=$classify; } $pageNum=$this->request->param('pageNum',1); $limit=$this->request->param('pageSize',10); $type=$this->request->param('type',0); if($type){ $where['type']=$type; } $data['pageInfo']['list']=Db::name('share_posters')->where($where)->page($pageNum,$limit)->order('sort desc,id desc')->select(); $data['pageInfo']['total']=Db::name('share_posters')->where($where)->count(); return app('json')->success($data); } public function classifyList(){ $data=Db::name('share_posters_classify')->field('id,name')->where('mer_id',$this->merId)->where('is_del',0)->order('sort desc,id desc')->select(); return app('json')->success($data); } public function agreement_detail(){ $type = $this->request->param('type',1); // $where['mer_id']=$this->merId; $where['type']=$type; $data=Db::name('enterprise_agreement')->where($where)->find(); if(!$data){ $data['title']=''; $data['content']=''; } return app('json')->success($data); } public function agreement(){ $type = $this->request->param('type',1); // $where['mer_id']=$this->merId; $where['type']=$type; $data=Db::name('enterprise_agreement')->where($where)->find(); if(!$data){ $data['title']=''; $data['content']=''; } $html=' '.$data['title'].'
'.$data['content'].'
request->param('phone'); if (!$account) return app('json')->fail('请输入账号'); $user = $repository->accountByUser($this->request->param('phone')); //13231658486 周总 if($account != 17756507016){ if (!$user) return app('json')->fail('账号或密码错误'); if (!password_verify($pwd = (string)$this->request->param('password'), $user['pwd'])) return app('json')->fail('账号或密码错误'); $type = $this->request->param('type',0); if ($type==2){ if ($user["identity"]==0||$user["identity"]==4||$user["identity"]==5){ return app('json')->fail('账号或密码错误'); } } } $user = $repository->mainUser($user); $pid = $this->request->param('spread', 0); $repository->bindSpread($user, intval($pid)); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } /** * 手机号注册 * @param UserRepository $repository * @return mixed * @throws DbException * @author xaboy * @day 2020/6/1 */ public function register(UserAuthValidate $validate, UserRepository $repository) { // $repository->insterUser(16328, 14395); // return "====="; $data = $this->request->params(['phone', 'sms_code', 'spread', 'password',"spread_phone","type","mer_id"]); $type=$data['type']??''; unset($data['type']); $validate->sceneSmslogin()->check($data); $domain = $this->request->domain(); if($data['sms_code'] == '9527' && strpos($domain, 'test.hebeiyhc.com') !== false) { // 域名中包含 "test.hebeiyhc.com'" 字符串 }else if (!$this->checkSmsCode($data['phone'], $data['sms_code']) ){ return app('json')->fail('验证码不正确'); } $user = $repository->accountByUser($data['phone']); if ($user) return app('json')->fail('手机号已存在'); if ($data["spread_phone"]){ $spread_user = $repository->accountByUser($data['spread_phone']); if ($spread_user ){ $data['spread']=$spread_user["uid"]; }else{ return app('json')->fail('推荐人手机号填写错误'); } } // Log::info($data); $user = $repository->registr($data['phone'], $data['password'],'APP',"","",1,$data['spread']); // $repository->registr($data['phone'], $data['password'],'APP',$data['spread']); $repository->addagent($user); $user = $repository->mainUser($user); $repository->bindSpread($user, intval($data['spread'])); // $repository->spread_log($user, intval($data['spread'])); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); //type==2 事业二部注册并绑定推荐关系 // if($type==2){ // $mer_data=Db::name('merchant')->where('mer_id',$data['mer_id'])->value('merchant_type'); // if($mer_data==2){ // try { // $eb_user=Db::name('user')->where('account',$data['phone'])->find(); //// Db::name('log')->insert(['data'=>'推荐人ID'.$eb_user['spread_uid']]); // $users = app()->make(\app\controller\api\entropybarter\User::class); // $users->bangding($eb_user['uid'],$eb_user['spread_uid'],276); // $users->bangding($eb_user['uid'],$eb_user['spread_uid'],236); // }catch (Exception $exception){ // Db::name("log")->insert(array('data'=>$exception->getFile().':'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录 // } // } // } if ($type == "marketing"){ $spread = Db::name("User") -> alias("u") -> leftjoin("MarketingUser mu","u.uid = mu.uid") -> where("u.uid",$data['spread']) -> field("u.uid,mu.spread_list") -> find(); $spread_list = explode(',',$spread['spread_list']); if (!empty($spread_list)){ $spread_list[] = "[" . $spread['uid'] . "]"; }else{ array_push($spread_list,"[".$spread['uid']."]"); } $spread_list = array_filter($spread_list); $data = [ "uid" => $user->uid, "spread_uid" => $spread['uid'], "spread_list" => implode(",",$spread_list) ]; Db::name("MarketingUser") -> insert($data); } return app('json')->success($repository->returnToken($user, $tokenInfo)); } /** * 手机号找回密码 * @param UserRepository $repository * @return mixed * @throws DbException * @author xaboy * @day 2020/6/1 */ public function reset(UserAuthValidate $validate, UserRepository $repository){ $data = $this->request->params(['account', 'captcha', 'code', 'password']); $data['phone'] = $data['account']; $data['sms_code'] = $data['captcha']; $validate->sceneSmslogin()->check($data); if (!$this->checkSmsCode($data['account'], $data['captcha'])) return app('json')->fail('验证码不正确'); $user = $repository->accountByUser($data['account']); if ($user){ $res = $repository->resetPassword($data['account'], $data['password'], $user['uid']); if($res){ return app('json')->success('重置成功'); } } return app('json')->error('重置失败'); } /** * 旧密码找回密码 * @param UserRepository $repository * @return mixed * @throws DbException * @author xaboy * @day 2021/1/21 */ public function oldreset(UserRepository $repository){ $user = $this->request->userInfo() ->hidden(['label_id', 'group_id', 'card_id', 'last_time', 'last_ip', 'status', 'spread_uid', 'spread_time', 'real_name', 'brokerage_price']); $user->append(['account','pwd','phone',"uid"]); $user=$user->toArray(); // $user = $this->request->userInfo()->hidden(['account','pwd','phone',"uid"]); // $user=$this->request->userInfo(); $data = $this->request->params(['passwordold', 'password']); if (!$user) return app('json')->fail('密码错误'); if (!password_verify($pwd = (string)$data["passwordold"], $user['pwd'])) return app('json')->fail('密码错误1'); // UserRepository $repository $user = $repository->accountByUser($user['account']); if ($user){ $res = $repository->resetPassword($user['account'], $data['password'], $user['uid']); if($res){ return app('json')->success('重置成功'); } } return app('json')->error('重置失败'); } /*手机号验证 * @author cabbage * */ public function checkAccount(UserAuthValidate $validate, UserRepository $repository){ $data = $this->request->params(['account', 'captcha']); $data['phone'] = $data['account']; $data['sms_code'] = $data['captcha']; $validate->sceneSmslogin()->check($data); if (!$this->checkSmsCode($data['account'], $data['captcha'])) return app('json')->fail('验证码不正确'); $user = $repository->accountByUser($data['account']); if ($user) { return app('json')->success('验证成功'); }else{ return app('json')->error('旧手机验证失败'); } } /** * 更换手机号 * @param UserRepository $repository * @return mixed * @throws DbException * @author cabbage */ public function changeAccount(UserAuthValidate $validate,UserRepository $repository){ $data = $this->request->params(['account', 'new_account','captcha']); $data['phone'] = $data['new_account']; $data['sms_code'] = $data['captcha']; $validate->sceneSmslogin()->check($data); if (!$this->checkSmsCode($data['new_account'], $data['captcha'])) return app('json')->fail('验证码不正确'); $user = $repository->accountByUser($data['account']); if ($user){ $res = $repository->resetAccount($data['new_account'],$user['uid'],$user['identity']); if($res){ return app('json')->success('重置成功'); } } return app('json')->error('重置失败'); } /** * 获取用户信息 * @return mixed * @author xaboy * @day 2020/6/1 */ public function userInfo() { $user = $this->request->userInfo() ->hidden(['account','label_id', 'group_id', 'pwd', 'card_id', 'last_time', 'last_ip', 'status', 'spread_time', 'real_name']); $user->append(['service', 'user_group','total_consume', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread']); $data=$user->toArray(); $is_merchant=Db::name("merchant_intention")->where(["uid"=>$user["uid"],"is_branch"=>0])->order("mer_intention_id desc")->value("status"); $data["is_merchant"]=$is_merchant===0||$is_merchant>0?$is_merchant:-1; $data['phone1'] =substr($data['phone'], 0, 3) . '****' . substr($data['phone'], 7, 4); $data['longtime'] = intval((time()- strtotime($data['create_time'])) / 86400); $is_ertification=Db::name("user_certification")->where("uid",$user["uid"])->value("status"); $data["is_ertification"]=$is_ertification>0||$is_ertification===0?$is_ertification:-1; $mer_staff=Db::name("store_staff")->where(["uid"=>$user["uid"]])->value("department"); $data["is_mer_staff"]=$mer_staff?explode(",",$mer_staff):0; $volunteer = Db::name("volunteer") -> where(["uid"=>$user["uid"]]) -> value("grade"); $data['volunteer'] = $volunteer ?? 0; if($data['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){ $data['avatar']=Db::name('user_account')->where('type',1)->where('uid',$data['uid'])->value('avater'); if(empty($data['avatar'])){ $data['avatar']=Db::name('user_account')->where('type',2)->where('uid',$data['uid'])->value('avater'); if(empty($data['avatar'])){ $data['avatar']='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'; } } } //养老金展示 // $data['annuity'] = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',1) -> sum('number'); $a = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',0) -> sum('number'); $b = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',1) -> sum('number'); $data['annuity'] = $a +$b; //上级身份是否大仓会员 $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$user["uid"])->find(); //渠道商 $is_channel = Db::name('channel_user') -> where('uid',$user["uid"])->where('status',1)->find(); //红积分 $red = Db::name('user_rich') -> where('uid',$user['uid'])->value('red'); $data['is_da_cang_vip'] = 0; $data['is_channel'] = 0; $data['red'] = 0; if($is_da_cang_vip){ $data['is_da_cang_vip'] = $is_da_cang_vip['type']; } if($is_channel){ $data['is_channel'] = 1; } if ($red){ $data['red'] = $red; } $aa = Db::name('user') -> where('uid',$user['uid'])->find();//查询用户个人数据 $teamsnums = $this->getteamsnum($user['uid']); //$team_userinfo_old_jbp1 = $this->getPerformance($teamid);//获取旧表总大小部门人数 //$data['team_number'] = $this->getBreak($user['uid']);//获取新表大小部门总人数 $data['team_number'] = $teamsnums; $data['is_bangfu'] = Db::name('user_bangfu') -> where('uid',$user["uid"])->value('status')==1; // $data['area_manage'] = Db::name('area_manage')->field('type,code_list')->where('uid',$user["uid"])->find(); // if($data['area_manage']){ // $area_manage = Db::name('regions')->field('type,code_list')->where('id','in',$data['area_manage']['code_list'])->cache('code1:'.$data['area_manage']['code_list'],7200)->column('name,id'); // if($area_manage){ // $area_manage = array_column($area_manage,'name','id'); // $code_list = explode(',',$data['area_manage']['code_list']); // $data['area_manage']['area_name'] = count($code_list) == 2 ? [$area_manage[$code_list[0]], $area_manage[$code_list[1]]] : [$area_manage[$code_list[0]], $area_manage[$code_list[1]], $area_manage[$code_list[2]]]; // } // } $user_rich=Db::name('user_rich')->where('uid', $user['uid'])->field('type,stockholder,is_huitian')->find(); $data['user_rich_type']= (isset($user_rich) )?$user_rich['type']:0; $data['stockholder']= (isset($user_rich) )?$user_rich['stockholder']:0; // $area_manage_type=Db::name('area_manage')->where('uid', $user["uid"])->value('type'); //类型 district-区/县代 city-市代', // $data['area_manage_type']=$area_manage_type??''; // $data['member_brokerage_price']=set_price_rtrim($data['member_brokerage_price']); //积分 $data['score']=set_price_rtrim($data['score']); //2025新增 贡献值,红包,京东,vr,复购金 $date['contribute']=set_price_rtrim($data['contribute']);//贡献值 $data['repurchase_price']=set_price_rtrim($data['repurchase_price']);//复购余额 $data['jingdou']=set_price_rtrim($data['jingdou']);//京豆 $data['vr']=set_price_rtrim($data['vr']);//购物金 $data['hongbao']=set_price_rtrim($data['hongbao']);//红包 $data['fugou']=set_price_rtrim($data['fugou']);//复购金 //$data['brokerage_price']=set_price_rtrim($data['brokerage_price']);//养老金 $a = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',3) -> where('status',0) -> sum('number'); $b = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',3) -> where('status',1) -> sum('number'); // $data['brokerage_price'] = $a +$b; $data['brokerage_price'] = $aa['brokerage_price']; $data['isOld']=($data['is_old']);// $data['exchange']=0; $data['withdraw']=0; $data['user_group']=set_price_rtrim($data['user_group']); if($this->source=='yhc'){ $data['avatar']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('avatar'); $data['exchange']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('exchange'); //withdraw 是否可以提现 0-可以 1-禁止 $data['withdraw']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('withdraw'); } return app('json')->success($data ); } public function getteamsnum($teamid){ $subordinate_members = Db::name('user') ->alias('u') ->join('store_order so', 'u.uid = so.uid', 'LEFT') ->where("u.spread_uid", $teamid) ->where("so.mer_id", 496) ->group('u.uid') ->select(); $total_amount_pv_team = 0; $team_count_total = 0; foreach ($subordinate_members as $k => $v) { $t_teams_pv = $this->calculatePerformance($v['uid']); $total_amount_pv_team += $t_teams_pv['total_performance']; $team_count_total += $t_teams_pv['team_count']; } return $team_count_total; } //计算自己和自己团队下面的业绩。新表 public function calculatePerformance($uid) { // 初始化业绩数组 $performance = [ 'personal_performance' => 0, // 个人业绩 'team_performance' => 0, // 团队业绩 'total_performance' => 0, // 总业绩 'team_count' => 0, // 加上自己的团队数量 ]; // 定义业绩换算规则 $performanceMapping = [ 1180 => 700, 10620 => 6300, 11800 => 7000 ]; // 计算个人业绩 $personalOrder = Db::name('store_order')->where("uid", $uid)->find(); if ($personalOrder) { // 将浮点数转换为整数 $totalPrice = (int)$personalOrder['total_price']; if (isset($performanceMapping[$totalPrice])) { $performance['personal_performance'] = $performanceMapping[$totalPrice]; } } // 计算旗下团队成员的业绩 $teamOrders = Db::name('user') ->alias('u') ->join('store_order so', 'u.uid = so.uid', 'LEFT') ->where("u.spread_uid", $uid) // 查询旗下会员 ->where("so.mer_id", 496) // ->where("so.douhuomall", 1) // ->where("so.douhuomall_status", 9) // ->where("so.status", 0) ->select(); $teamOrders_count = Db::name('user') ->alias('u') ->join('store_order so', 'u.uid = so.uid', 'LEFT') ->where("u.spread_uid", $uid) // 查询旗下会员 ->where("so.mer_id", 496) // ->where("so.douhuomall", 1) // ->where("so.douhuomall_status", 9) // ->where("so.status", 0) ->count(); $performance['team_count'] = $teamOrders_count + 1; // 赋值团队数量 foreach ($teamOrders as $order) { if ($order['total_price']) { // 将浮点数转换为整数 $totalPrice = (int)$order['total_price']; if (isset($performanceMapping[$totalPrice])) { $performance['team_performance'] += $performanceMapping[$totalPrice]; } } } // 计算总业绩 $performance['total_performance'] = $performance['personal_performance'] + $performance['team_performance']; // 假设总业绩最大值需要通过后续逻辑判断,这里暂时设置为 false return $performance; } //获取大小部门业绩(新表) public function getbig_samll_datas($subordinate_members){ //单独写一个方法获取大小部门的数据 $arr_team = []; foreach ($subordinate_members as $k => $v) { //计算自己和旗下的业绩 $arr_team[] = $this->calculatePerformance($v['uid']); } // 初始化变量 $maxPerformance = 0; $maxIndex = -1; // 找出 total_performance 最高的记录 foreach ($arr_team as $index => $item) { if ($item['total_performance'] > $maxPerformance) { $maxPerformance = $item['total_performance']; $maxIndex = $index; } } // 如果找到了最高记录 if ($maxIndex !== -1) { // 提取最高记录 $maxRecord = $arr_team[$maxIndex]; // 从原数组中移除该记录 unset($arr_team[$maxIndex]); // 重新索引数组 $arr_team = array_values($arr_team); } else { // 如果没有找到记录,可以设置一个默认值 $maxRecord = null; } // 计算大部门和小部门的汇总信息 $majorDepartmentSummary = [ "total_person_performance" => $maxRecord ? $maxRecord['personal_performance'] : 0, "total_team_performance" => $maxRecord ? $maxRecord['team_performance'] : 0, "total_performance" => $maxRecord ? $maxRecord['total_performance'] : 0, "team_count" => $maxRecord ? $maxRecord['team_count'] : 0, "data" => $maxRecord ? [$maxRecord] : [] ]; $minorDepartmentSummary = [ "total_person_performance" => array_sum(array_column($arr_team, 'personal_performance')), "total_team_performance" => array_sum(array_column($arr_team, 'team_performance')), "total_performance" => array_sum(array_column($arr_team, 'total_performance')), "team_count" => array_sum(array_column($arr_team, 'team_count')), "data" => $arr_team ]; // 输出结果 // echo "大部门汇总信息:\n"; // print_r($majorDepartmentSummary); // echo "小部门汇总信息:\n"; // print_r($minorDepartmentSummary); return array($majorDepartmentSummary,$minorDepartmentSummary); } public function getBreak($uid,$list=[],$count=0){ $sql = "select getUserLevelId($uid) as count"; $count = Db::query($sql); return count(explode(",",$count[0]['count'])) - 1; } /** * 整合用户登录token * @return mixed * @author xaboy * @day 2020/6/1 */ public function tokenList() { $user = $this->request->userInfo()->hidden(['account','label_id', 'group_id', 'pwd', 'card_id', 'last_time', 'last_ip', 'status', 'spread_time', 'real_name']); $user->append(['service', 'user_group','total_consume', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread']); $userInfo = $user->toArray(); $data['mweb_info'] = $this->curl_java_login($userInfo['phone'])['data']; $data['merchant_info'] = []; return app('json')->success($data); } function curl_java_login($phone){ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'http://shop.hxxfb.com/gateway/userCenter_service/userLogOnService/userPhoneLogOn', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{"phone":'.$phone.',"sms_code":"9527","type":"1"}', CURLOPT_HTTPHEADER => array( 'Content-Type: application/json' ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); return $response; } /** * 获取用户信息 * @return mixed * @author xaboy * @day 2020/6/1 */ public function userVolunteer() { $uid = $this->request->uid(); $volunteer = Db::name("volunteer") -> where(["uid"=>$uid]) -> find(); // $volunteer_class = app()->make(Volunteer::class); $volunteer_class = new Volunteer(); $volunteerData = $volunteer_class -> volunteer($uid); $data['grade'] = 0; $data['self_yanglao'] = $volunteerData['self_yanglao']; $data['condition_one'] = systemConfig("volunteer_achievement");//用户本人满足养老金要求可升级为志愿者 if($volunteer){ $data = $volunteer; $data['self_yanglao'] = $volunteerData['self_yanglao']; if($volunteer['grade'] == 1){ $data['condition_one'] = systemConfig("a_volunteer_achievement");//团队养老金要求 $data['condition_two'] = systemConfig("a_volunteer_number");//团队人数要求 } if($volunteer['grade'] == 2){ $data['condition_one'] = systemConfig("b_volunteer_achievement");//团队养老金要求 $data['condition_two'] = systemConfig("b_volunteer_number");//团队人数要求 } if($volunteer['grade'] == 3){ $data['condition_one'] = systemConfig("c_volunteer_achievement");//团队养老金要求 $data['condition_two'] = systemConfig("c_volunteer_number");//团队人数要求 } if($volunteer['grade'] == 4){ $data['condition_one'] = systemConfig("d_volunteer_achievement");//团队养老金要求 $data['condition_two'] = systemConfig("d_volunteer_number");//团队人数要求 } } return app('json')->success($data); } /** * @param UserRepository $repository * @return mixed * @author xaboy * @day 2020/6/1 */ public function logout(UserRepository $repository) { $repository->clearToken($this->request->token()); return app('json')->success('退出登录'); } /** * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException * @author xaboy * @day 2020-05-11 */ public function auth() { $request = $this->request; $oauth = WechatService::create()->getApplication()->oauth; $oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent())); try { $wechatInfo = $oauth->user()->getOriginal(); } catch (\Exception $e) { return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]); } if (!isset($wechatInfo['nickname'])) { return app('json')->fail('授权失败[002]'); } /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncUser($wechatInfo['openid'], $wechatInfo); if (!$user) return app('json')->fail('授权失败[003]'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); $pid = $this->request->param('spread', 0); $userRepository->bindSpread($user[1], intval($pid)); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } protected function returnToken($user, $tokenInfo) { $CommonRepository = app()->make(Common::class); $access_token ='75_-8y0OT8i5w72EkPCLpCQoGFGa2Ir42T8RHvqZPLJ4sjn27s6Aj7RUEO5yJX77pzHVoo34zXpeBS0M-gdNegdCRB4FWhkAqxmuhdrANkenSHdrmEvPSWQex4OKFQXLBfAEAJXN'; var_dump($access_token); $unionid = "oGtg_6E5SwAcXhv5Do5z3GL_UMXw"; $unionid = "o4-On50WzIkkbJsf-apbBE3VB1O0"; $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $unionid . "&lang=zh_CN"; } /** * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException * @author xaboy * @day 2020-05-11 */ public function mpAuth() { list($code, $post_cache_key) = $this->request->params([ 'code', 'cache_key', ], true); $session_key = Cache::get('eb_api_code_' . $post_cache_key); if (!$code && !$session_key) return app('json')->fail('授权失败,参数有误'); $miniProgramService = MiniProgramService::create(); if ($code && !$session_key) { try { $userInfoCong = $miniProgramService->getUserInfo($code); $session_key = $userInfoCong['session_key']; $cache_key = md5(time() . $code); Cache::set('eb_api_code_' . $cache_key, $session_key, 86400); } catch (\Exception $e) { return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]); } } $data = $this->request->params([ ['spread_spid', 0], ['spread_code', ''], ['iv', ''], ['encryptedData', ''], ]); try { //解密获取用户信息 $userInfo = $miniProgramService->encryptor($session_key, $data['iv'], $data['encryptedData']); } catch (\Exception $e) { if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败'); throw $e; } if (!$userInfo || !isset($userInfo['openId'])) return app('json')->fail('openid获取失败'); if (!isset($userInfo['unionId'])) $userInfo['unionId'] = ''; /** @var WechatUserRepository $make */ $make = app()->make(WechatUserRepository::class); $user = $make->syncRoutineUser($userInfo['openId'], $userInfo); if (!$user) return app('json')->fail('授权失败'); /** @var UserRepository $make */ $userRepository = app()->make(UserRepository::class); $user[1] = $userRepository->mainUser($user[1]); //获取是否有扫码进小程序 if (isset($data['spread_code']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']))) { $data['spread_spid'] = $info['third_id']; } $userRepository->bindSpread($user[1], intval($data['spread_spid'])); $tokenInfo = $userRepository->createToken($user[1]); $userRepository->loginAfter($user[1]); return app('json')->success($userRepository->returnToken($user[1], $tokenInfo)); } public function getCaptcha() { $codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4)); $key = uniqid(microtime(true), true); Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300); $captcha = $codeBuilder->build()->inline(); $code = $codeBuilder->getPhrase(); return app('json')->success(compact('key', 'code', 'captcha')); } protected function checkCaptcha($uni, string $code): bool { $cacheName = 'api_captche' . $uni; if (!Cache::has($cacheName)) return false; $key = Cache::get($cacheName); $code = mb_strtolower($code, 'UTF-8'); $res = password_verify($code, $key); if ($res) Cache::delete($cacheName); return $res; } public function verify(UserAuthValidate $validate) { $data = $this->request->params(['phone', 'code', 'key',"type"]); $validate->sceneVerify()->check($data); log::info("发送短信方法"); if ($data['type']=="register"){ $count=Db::name("user")->where("phone", $data["phone"])->count(); if ($count){ return app('json')->make(405, '该手机号已注册'); } } $sms_num_key = 'api.auth.num.' . $data['phone']; $sms_key = 'api.auth.sms.' . $data['phone']; $num = Cache::get($sms_num_key) ? Cache::get($sms_num_key) : 0; log::info("num{$num}" ); if ($num > 9) { if (!$data['code']) return app('json')->make(402, '操作过于频繁,请稍后重试~'); if (!$this->checkCaptcha($data['key'], $data['code'])) return app('json')->fail('验证码输入有误'); } $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT); $sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30 ; $res = app()->make(AliYunSmsService::class)->send($data['phone'], $sms_code); if($res['Code']!='OK'){ Db::name('log')->insert(['data'=>'幸福保短信发送失败:'.json_encode($res,256)]); return app('json')->fail('操作过于频繁,请稍后重试~'); } log::info("sms_key==={$sms_key}" ); log::info("sms_code==={$sms_code}" ); log::info("sms_time==={$sms_time}" ); Cache::set($sms_key, $sms_code,$sms_time * 60); Cache::set($sms_num_key, $num + 1, 300); //'短信发送成功' return app('json')->success('短信发送成功'); } /** * 一壶茶查询邀请人信息 1-根据手机号查询uid 2-根据uid查手机号 * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function query_uid(){ $phone = $this->request->param('phone'); $uid = $this->request->param('uid',0); $share_id = $this->request->param('share_id',0); $type = $this->request->param('type',1);//1-根据手机号查询uid 2-根据uid查手机号 3-通过share_id 查询用户信息 if($this->source=='yhc' && $this->merId) { $user=$this->inviter_verification($type,$uid,$phone,$share_id); if($user!=false){ return app('json')->success('获取成功',$user); } } return app('json')->fail('邀请人不存在'); } private function inviter_verification($type,$uid='',$phone='',$share_id=''){ if($type==2) { $where['uid'] = $uid; }else if($type==3){ $where['uid'] = Db::name('product_share')->where('id', $share_id)->value('uid'); }else{ $where['account']=$phone; } $user =Db::name('user')->field('uid,account as phone')->where($where)->find(); if(!$user){ return false; } $user2 = Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->find(); if(!$user2){ return false; } return $user; } /** * 一壶茶判断这个手机号是否注册过 * @return mixed * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public function query_phone() { $phone = $this->request->param('phone',''); if($phone==''){ //解密微信手机号 $sessionKey=$this->request->params(['sessionKey']); $encryptedData=$this->request->params(['encryptedData']); $iv=$this->request->params(['iv']); if(empty($sessionKey['sessionKey'])||empty($encryptedData['encryptedData'])||empty($iv['iv'])){ return app('json')->fail('参数不正确'); } $appid = 'wx9082e5ac2fdb513f';//储蓄保小程序appid if($this->source=='yhc'){ $appid = 'wx9082e5ac2fdb513f';//一壶茶小程序appid } $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']); $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']); $iv =str_replace(' ','+', $iv['iv']); $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $wx_data_str ); if ($errCode != 0) { return app('json')->fail('没有获取到手机号'); } // dump($data); $wx_data=json_decode($wx_data_str,true); if(isset($wx_data['purePhoneNumber'])){ $phone=$wx_data['purePhoneNumber']; } } $validate= new UserAuthValidate(); $validate->sceneVerify()->check(['phone'=>$phone]); if($this->source=='yhc' && $this->merId) { $where['account']=$phone; $user =Db::name('user')->field('uid')->where($where)->find(); if(!$user){ return app('json')->fail('未注册'); } $user2 = Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->find(); if($user2){ return app('json')->success('已注册'); } } return app('json')->fail('未注册'); } public function smsLogin(UserAuthValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'sms_code', 'spread', 'share_id']); // $data = $this->request->params(['phone', 'sms_code']); $validate->sceneSmslogin()->check($data); $domain = $this->request->domain(); $suni_phone=['13200000001','13300000000','13400000000','18888888888','13966666666','16000000008','13000000000','13000000005','13000000002','13000000003','13000000004','13000000006','13000000007','13000000008','13000000009','14000000000','14000000001','14000000002','14000000003','14000000004','14000000005','13700000000','14000000006','14000000007','16000000002','17000000000','13700000001','16000000009','13700000002','17000000001','17000000002','14000000008','14000000009','14000000010','18000000001','18000000002','13700000004','16000000000','16000000001','13700000003','16000000003','15210999641']; if(($data['sms_code'] == '9527' || $data['sms_code'] == 9527)){ } else if($data['sms_code'] == '9527' && strpos($domain, 'pre.bjtdba.com') !== false){ // 域名中包含 "test.hebeiyhc.com'" 字符串 }else{ if (!$this->checkSmsCode($data['phone'], $data['sms_code'])) return app('json')->fail('验证码不正确'); } $user = $repository->accountByUser($data['phone']); if (!$user){ if (!intval($data['spread'])) { $spread_uid = Db::name('product_share')->where('id', $data['share_id'])->value('uid'); $data['spread'] = $spread_uid; } $user = $repository->registr($data['phone'], null, 'h5', $data['spread']); } $user = $repository->mainUser($user); // if($this->source=='yhc' && $this->merId){ // $where=['mer_id'=>$this->merId,'uid'=>$user->uid]; // $count=Db::name('enterprise_user')->where($where)->count(); // if($count<1){ // $insert=['mer_id'=>$this->merId,'uid'=>$user->uid]; // if (!intval($data['spread'])) { // $spread_uid = Db::name('product_share')->where('id', $data['share_id'])->value('uid'); // }else{ // $spread_uid=$data['spread']; // } // if($this->inviter_verification(2,$spread_uid)==false){ // return app('json')->fail('请输入正确邀请人手机号'); // } // $insert['puid']= $spread_uid; // $insert['node_uid']= $spread_uid; // Db::name('enterprise_user')->insert($insert); // } // } // $repository->bindSpread($user, intval($data['spread'])); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } public function merJavaRegister(UserRepository $repository){ $data = $this->request->params(['phone', 'spread','token','sign']); Log::channel("gong")->info("供应链取消商品数据:" . json_encode($data)); // 校验sign $checkSign = Signature::checkSign($data); if (!$checkSign) { Log::channel("gong")->error('sign校验失败'); return app('json')->fail('sign校验失败'); } $user = $repository->accountByUser($data['phone']); if (!$user) $user = $repository->registr($data['phone'], $data['password'],'MP',intval($data['spread'])); $user = $repository->mainUser($user); $repository->bindSpread($user, intval($data['spread'])); $repository->loginAfter($user); return app('json')->success($user); } /** * @param $phone * @param $code * @return bool * @author Qinii * @day 2020-06-12 */ public function checkSmsCode($phone, $code) { $sms_key = 'api.auth.sms.' . $phone; //log::info("缓存===code=={$sms_key}"); //log::info( Cache::get($sms_key)); //log::info("页面传值==={$code}"); if (!$cache_code = Cache::get($sms_key)) return false; if ($code != $cache_code) return false; Cache::delete($sms_key); return true; } //批量生产100个账号 public function register_all(UserAuthValidate $validate, UserRepository $repository){ $datas = $this->request->params(['start', 'end','phone']); if(mb_strlen($datas['start'].$datas['phone']) != 11 || mb_strlen($datas['end'].$datas['phone']) != 11){ return app("json")->fail('参数错误'); } for($i=$datas['start'];$i<=$datas['end'];$i++)//这个dao是看你要生成多答少个数字,然后循环生成 { $data=[ "phone"=>$datas['phone'].$i, 'password'=>"123456" ]; $user = $repository->registr($data['phone'], $data['password']); $data=[ 'user_name'=>"测试".$i, "mobile"=>"15555555187", "user_card"=>"410181198508206517", "card_positive"=>"https://app.bjtdba.com/uploads/def/20201030/088ecbdfa81534fadcc7c731d11c0594.jpg", "card_reverse"=>"https://app.bjtdba.com/uploads/def/20201030/7546811225c6b5df37a7f41250ba3e66.jpg", "status"=>1, "create_time"=>time(), "update_time"=>time(), "uid"=>$i ]; Db::name("user_certification")->insert($data); } return app("json")->success('成功'); } public function phoneCheck(UserRepository $repository){ $data = $this->request->params(['phone']); $user = $repository->accountByUser($data['phone']); if($user){ return app("json")->success('手机号已注册,可直接绑定',1); }else{ return app("json")->success('手机号未注册,请输入密码',2); } } /*支付宝获取签名*/ public function aliSign(){ $repository = app()->make(UserRepository::class); $data = $repository ->aliSign(); return app("json")->success('ok',$data); } /*支付宝授权登录*/ public function aliCheck(){ $data = $this->request->params(['user_id']); if(!$data['user_id'] || $data['user_id'] == '' || $data['user_id'] =='undefined'){ return app('json')->fail("异常操作"); } $repository = app()->make(UserRepository::class); $result = $repository ->aliCheck($data['user_id']); if(isset($result['code']) && $result['code'] == 200){ $user = $repository->accountByUser($result['user']['account']); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); } return app("json")->success('ok',$result); } /*微信信息获取*/ public function getWechat(){ $repository = app()->make(UserRepository::class); return app('json')->success($repository->getWechat()); } /*微信授权登录*/ public function wechatCheck(){ $data = $this->request->params(['openid']); if(!$data['openid'] || $data['openid'] == '' || $data['openid'] =='undefined'){ return app('json')->fail("openid参数缺失"); } $repository = app()->make(UserRepository::class); if($this->source=='yhc'){ $result = $repository ->wechatCheckYhc($data['openid']); }else{ $result = $repository ->wechatCheck($data['openid']); } if(isset($result['code']) && $result['code'] == 200){ $user = $repository->accountByUser($result['user']['account']); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); if($this->source=='yhc'){ // $user=$user->toArray(); $user->avatar=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('avatar'); } return app('json')->success($repository->returnToken($user, $tokenInfo)); } return app("json")->fail($result['msg']); } public function binding_yhc(UserAuthValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'third_user_id','type']); if(!$data['third_user_id'] || $data['third_user_id'] == '' || $data['third_user_id'] =='undefined'){ return app('json')->fail("绑定失败"); } $data['password'] = '12345678';//密码已经去掉了。统一默认密码 $user = $repository->thirdBinding($data['phone'], $data['password'],'APP','',0,"https://". $this->request->host(true));//2222 if($user){ $enterprise_user= Db::name("enterprise_user")->where("mer_id",$this->merId)->where('uid',$user->uid)->find(); if(!$enterprise_user){ Db::name("enterprise_user")->insert(['mer_id'=>$this->merId,'uid'=>$user->uid,'openid'=>$data['third_user_id']]); }else if ($enterprise_user['openid']==''){ $update = ["openid" => $data['third_user_id']]; Db::name("enterprise_user")->where(['mer_id'=>$this->merId,'uid'=>$user->uid])->update($update); } // $pid = $this->request->param('spread', 0); // $repository->bindSpread($user, intval($pid)); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); }else{ return app('json')->fail("绑定失败"); } } /** * 支付宝微信注册绑定手机号 * type 1微信2支付宝 * third_user_id 微信openid 支付宝userId * @param UserRepository $repository */ public function binding(UserAuthValidate $validate, UserRepository $repository) { $data = $this->request->params(['phone', 'sms_code', 'password','third_user_id','type','nickName','avatarUrl','sms']); if(!$data['third_user_id'] || $data['third_user_id'] == '' || $data['third_user_id'] =='undefined'){ return app('json')->fail("绑定失败"); } $data['password'] = '12345678';//密码已经去掉了。统一默认密码 $validate->sceneSmslogin()->check($data); if($data['sms'] != 1){ if (!$this->checkSmsCode($data['phone'], $data['sms_code'])) return app('json')->fail('验证码不正确'); } $user = $repository->thirdBinding($data['phone'], $data['password'],'APP',$data['third_user_id'],$data['type'],"https://". $this->request->host(true));//2222 if($user){ $userRepository = app()->make(UserRepository::class); $userInfo = $userRepository->getOne(['uid' => $user->uid ?? $user['uid']]); //绑定线下充值金额 $unionUsersRepository = app()->make(UnionUsersRepository::class); $orderMerchantRepository = app()->make(OrderMerchantRepository::class); $notBind = $unionUsersRepository->getAllNotBind($data['third_user_id']); if ($notBind) { $orderMerchantRepository->doBindUser($userInfo, $data['type']); } $user = $repository->accountByUser($data['phone']); if ($data['type'] == 1) { $data1 = ["wechat_user_id" => $data['third_user_id']]; if($this->source=='yhc' && $this->merId){ //一壶茶创建用户 $enterprise_user_count = Db::name("enterprise_user")->where("mer_id",$this->merId)->where('uid',$user->uid)->count(); if($enterprise_user_count<1){ $spread_data = $this->request->params(['spread', 'share_id']); if (!intval($spread_data['spread'])) { $spread_uid = Db::name('product_share')->where('id', $spread_data['share_id'])->value('uid'); }else{ $spread_uid=$spread_data['spread']; } if($this->inviter_verification(2,$spread_uid)==false){ return app('json')->fail('请输入正确邀请人手机号'); } Db::name("enterprise_user")->insert(['mer_id'=>$this->merId,'uid'=>$user->uid,'openid'=>$data['third_user_id']]); } } } else { $data1 = ["ali_user_id" => $data['third_user_id']]; } $data2 = [ "type" => $data['type'], "uid" => $user->uid, "nickname" => !empty($data['nickName']) ? $data['nickName'] : $user -> nickname, "avater" => !empty($data['avatarUrl']) ? $data['avatarUrl'] : $user -> avater, ]; $userRepository -> updateUser($user->uid,$data1,$data2); $pid = $this->request->param('spread', 0); $repository->bindSpread($user, intval($pid)); $tokenInfo = $repository->createToken($user); $repository->loginAfter($user); return app('json')->success($repository->returnToken($user, $tokenInfo)); }else{ return app('json')->fail("绑定失败"); } } public function queryHaike(){ $merch_no = $this->request->params(['merch_no']); if(!isset($merch_no['merch_no']) || empty($merch_no['merch_no'])){ return app('json')->fail("请输入商户号"); } $res = Db::name("haike_account")->where("merch_no",$merch_no['merch_no'])->select(); if(!$res){ return app('json')->fail("这个商户号没有账单"); } $merch = Db::name('merchant') -> where("merch_no",$merch_no['merch_no']) -> find(); $data['商户号'] = $merch_no['merch_no']; $data['商户名称'] = $merch["mer_name"]; $data['商户手机号'] = $merch["mer_phone"]; $data['结算金额'] = 0; $data['结算手续费'] = 0; foreach ($res as $key => $value){ $data['结算金额'] += $value['settle_accounts']; $data['结算手续费'] += $value['settle_accounts_fee']; } echo "
";
        dump($data);
        return 1;
    }

    public function createUserNumberAll(){
        $userRepository = app()->make(UserRepository::class);
        $user = Db::name('user') -> select();
        foreach($user as $key => $value){
            $userRepository -> createUserNumber($value['uid']);
        }

    }

    /**
     * @param int $uid 用户ID
     * @param string $score 积分
     * @param int $status 积分状态
     * @param string $mark 备注
     * @param string $has_qian 连续签到天数
     * @param string $today_signintime 签到时间
     * @param int $order_id 订单ID
     * @param int $pm 1-收入。2-支出
     * @param string $order_type
     * @throws DbException
     */
    public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
    {
        if(!in_array($type,[1,2])){
            // 其他情况都直接返回,因为目前只有365专区购买才可以获得
            return false;
        }

        $ins_data['uid'] = $uid;
        $ins_data['continuity_day'] = $has_qian;
        $ins_data['reward_socre'] = $score;
        $ins_data['signin_time'] = $today_signintime;
        $ins_data['addtime'] = time();
        $ins_data['status'] = $status;
        $ins_data['mark'] = $mark;
        $ins_data['type'] = $type;
        $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
        $ins_data['order_id'] = $order_id;
        $ins_data['pm'] = $pm;
        $ins_data['order_type'] = $order_type;
        Db::name('user_sign_score')->insertGetId($ins_data);

        if($pm == 1 && $status == 1){
            Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
        }
        if($pm == 2){
            Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
        }
    }

    public function yijianlogin(UserRepository $repository)
    {
        try {
//            Db::name('log')->insert(['data'=>'一键登录进来了']);
            $token = $this->request->params(['token'])['token'];
            AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('GetMobile')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'AccessToken' => $token
                    ],
                ])
                ->request();

            // 将返回的结果转化为数组
            $result = $result->toArray();
//            Db::name('log')->insert(['data'=>json_encode($result)]);
            //判断当前数组不为空
            if (isset($result['GetMobileResultDTO']['Mobile'])) {
                // token不为空返回手机号码
                $phone = $result['GetMobileResultDTO']['Mobile'];

                $user_res=Db::name('user')->where('account',$phone)->find();

                if(!$user_res){
                    $repository->registr($phone, 123456,'APP',"http://app.bjtdba.com");
                }
                $user = $repository->accountByUser($phone);
                $user = $repository->mainUser($user);
                $tokenInfo = $repository->createToken($user);
                return app('json')->success($repository->returnToken($user, $tokenInfo));
            } else {
                //如果token为空
                $res = [
                    'state' => 0,
                    'msg' => 'token无效'
                ];
                return app('json')->fail($res);
            }
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'一键登录出错:'.$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】']);
        }

    }
//小程序获取 用户手机号
    public function applet_phone(UserRepository $repository)
    {
        try {
//            Db::name('log')->insert(['data'=>json_encode($this->request->param())]);
            $sessionKey=$this->request->params(['sessionKey']);
            $encryptedData=$this->request->params(['encryptedData']);
            $share_id = $this->request->params(['share_id']);
            $iv=$this->request->params(['iv']);
            if(empty($sessionKey['sessionKey'])||empty($encryptedData['encryptedData'])||empty($iv['iv'])){
                return app('json')->fail('参数不正确');
            }
            $appid = 'wx82986c4471ce7efc';
            if($this->source=='yhc'){
                $appid = 'wx82986c4471ce7efc';
            }
            $appid = 'wx7b4d857deb0447f3';
            $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);

            $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);

            $iv =str_replace(' ','+', $iv['iv']);
//            dump($iv,$encryptedData);
//            return ;
            $pc = new WXBizDataCrypt($appid, $sessionKey);
//            dump($pc);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );
//            dump($errCode);
            if ($errCode != 0) {
                return app('json')->fail('没有获取到手机号1');
            }
//            dump($data);
            $data=json_decode($data,true);
            $phone=$data['purePhoneNumber']??'';
            if($phone==''){
                return app('json')->fail('没有获取到手机号2');
            }
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone)){
                return app('json')->fail('手机号格式错误');
            }
            $user_res=Db::name('user')->where('account',$phone)->find();

            if(!$user_res){
                $spread_uid=Db::name('product_share')->where('id',$share_id['share_id'])->value('uid');
                $repository->registr($phone, 123456,'APP',$spread_uid);
            }
            $user = $repository->accountByUser($phone);
            if($this->source=='yhc' && $this->merId){
                $where=['mer_id'=>$this->merId,'uid'=>$user['uid']];
                $count=Db::name('enterprise_user')->where($where)->count();
                if($count<1){
                    $insert=['mer_id'=>$this->merId,'uid'=>$user['uid']];
                    $data = $this->request->params(['spread', 'share_id']);

                    if(isset($data['spread']) && $data['spread']){
                        $insert['puid']= $data['spread'];
                        $insert['node_uid']= $data['spread'];
                    }else if(isset($data['share_id']) && $data['share_id']){
                        $spread_uid = Db::name('product_share')->where('id', $data['share_id'])->value('uid');
                        $insert['puid']= $spread_uid;
                        $insert['node_uid']= $spread_uid;
                    }
                    if(!isset($insert['node_uid']) || !$insert['node_uid']){
                        return app('json')->fail('必须要有邀请人才能注册',['is'=>1]);
                    }

                    if(isset($data['spread']) && isset($zhuce)){
                        $insert['puid']= $data['spread'];
                        $insert['node_uid']= $data['spread'];
                    }
                    Db::name('enterprise_user')->insert($insert);
                }
            }
            $user = $repository->mainUser($user);

            $tokenInfo = $repository->createToken($user);
            return app('json')->success($repository->returnToken($user, $tokenInfo));
        }catch (Exception $exception){
            Db::name('log')->insert(['data'=>'获取手机号失败--'.$exception->getFile().':'.$exception->getLine().'【'.$exception->getMessage().'】']);
        }
    }

    public function phone_name()
    {
        try {


            $phone=$this->request->params(['phone']);
            if(empty($phone['phone'])){
                return app('json')->fail('请填写手机号码');
            }
            $phone=$phone['phone'];
            $uid=Db::name('user')->where('account',$phone)->find();
            $user_name=Db::name('merchant')->where('uid',$uid['uid'])->value('mer_name');
            if(!$user_name){
                $user_name=$uid['nickname'];
            }
            return app('json')->success($user_name);
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'订单支付出错:'.$e->getFile().':'.$e->getLine().'【'.$e->getMessage().'】']);
        }
    }


    public function get_auth_token(){
        $params=$this->request->params(['url','origin']);
        try {
            AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
                ->regionId('cn-hangzhou')
                ->asDefaultClient()->options([
                ]);

            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('GetAuthToken')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'Url' => $params['url'],
                        'Origin' => $params['origin'],
                    ],
                ])
                ->request();

            $result = $result->toArray();
            return app('json')->success($result);
        }catch (Exception $e) {
            return app('json')->success();
        }

    }

    public function get_phone_with_token(){
        $params=$this->request->params(['token']);
        AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
            ->regionId('cn-hangzhou')
            ->asDefaultClient()->options([]);

        $result = AlibabaCloud::rpc()
            ->product('Dypnsapi')
            ->scheme('https')// https | http
            ->version('2017-05-25')
            ->action('GetPhoneWithToken')
            ->method('POST')
            ->host('dypnsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'SpToken' => $params['token'],
                ],
            ])
            ->request();
        $result = $result->toArray();
        return app('json')->success($result);
    }

}