Autotask.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. <?php
  2. namespace addons\qingdong\controller;
  3. use addons\qingdong\model\AdminConfig;
  4. use addons\qingdong\model\AttendanceRule;
  5. use addons\qingdong\model\AttendanceStatisc;
  6. use addons\qingdong\model\AttendanceTime;
  7. use addons\qingdong\model\Message;
  8. use addons\qingdong\model\Customer;
  9. use addons\qingdong\model\Event;
  10. use addons\qingdong\model\Staff;
  11. use addons\qingdong\model\Leads;
  12. use addons\qingdong\model\Attendance;
  13. use think\Db;
  14. use think\Exception;
  15. use think\Log;
  16. use think\Session;
  17. use addons\qingdong\model\StaffDepartment;
  18. use addons\qingdong\model\DingStaff;
  19. use addons\qingdong\model\DingCustomer;
  20. use addons\qingdong\model\DingContacts;
  21. use addons\qingdong\model\DingRecord;
  22. use addons\qingdong\library\Ding;
  23. use addons\qingdong\library\Wechat;
  24. use addons\qingdong\library\WechatEnterprise;
  25. use addons\qingdong\model\WechatOpenid;
  26. /**
  27. * 定时任务
  28. */
  29. class Autotask extends \think\addons\Controller
  30. {
  31. protected $noNeedLogin = ["*"];
  32. protected $layout = '';
  33. public function _initialize()
  34. {
  35. parent::_initialize();
  36. if (!$this->request->isCli()) {
  37. $this->error('只允许在终端进行操作!');
  38. }
  39. }
  40. /**
  41. * 合同
  42. */
  43. public function contract()
  44. {
  45. $endDate = date('Y-m-d', strtotime('+3 day'));
  46. $contracts = \addons\qingdong\model\Contract::where(['check_status' => 2, 'contract_status' => 0, 'end_time' => ['lt', $endDate]])->select();
  47. try {
  48. //合同即将到期通知
  49. foreach ($contracts as $v) {
  50. Message::addMessage(Message::CONTRACT_EXPIRE_TYPE, $v['id'], $v['owner_staff_id'], '');
  51. }
  52. } catch (Exception $e) {
  53. return $e->getMessage();
  54. }
  55. $this->plan();
  56. return 'success';
  57. }
  58. /**
  59. * 回款计划通知
  60. */
  61. public function plan()
  62. {
  63. $endDate = date('Y-m-d', strtotime('+1 day'));
  64. //进行中 -- 待回款
  65. $plans = \addons\qingdong\model\ReceivablesPlan::where(['status' => 0, 'remind_date' => ['lt', $endDate]])->select();
  66. try {
  67. //回款计划即将到期通知
  68. foreach ($plans as $v) {
  69. Message::addMessage(Message::PLAN_EXPIRE_TYPE, $v['contract_id'], $v['owner_staff_id'], '');
  70. }
  71. } catch (Exception $e) {
  72. return $e->getMessage();
  73. }
  74. return 'success';
  75. }
  76. /**
  77. * 公海
  78. */
  79. public function seas()
  80. {
  81. if (AdminConfig::getConfigValue('auto', AdminConfig::TYPE_SEAS)) {//自动回收客户
  82. if (AdminConfig::getConfigValue('genjing', AdminConfig::TYPE_SEAS) == 1) {//未跟进客户回收
  83. $day = AdminConfig::getConfigValue('genjing_day', AdminConfig::TYPE_SEAS);
  84. $where['last_time'] = ['<', date('Y-m-d H:i:s', strtotime('-' . $day . ' day'))];
  85. if (AdminConfig::getConfigValue('genjing_success', AdminConfig::TYPE_SEAS) == 1) {
  86. $where['contract_status'] = 0;
  87. }
  88. $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
  89. try {
  90. foreach ($customers as $c) {
  91. Customer::moveSeas($c['id']);
  92. Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0);
  93. }
  94. } catch (Exception $e) {
  95. Log::error($e->getMessage());
  96. }
  97. }
  98. if (AdminConfig::getConfigValue('chengjiao', AdminConfig::TYPE_SEAS) == 1) {//未成交客户回收
  99. $day = AdminConfig::getConfigValue('chengjiao_day', AdminConfig::TYPE_SEAS);
  100. $where = [
  101. 'receivetime' => ['<', date('Y-m-d H:i:s', strtotime('-' . $day . ' day'))],
  102. 'contract_status' => 0
  103. ];
  104. $customers = Customer::where($where)->field('id,name,owner_staff_id')->select();
  105. try {
  106. foreach ($customers as $c) {
  107. Customer::moveSeas($c['id']);
  108. Message::addMessage(Message::SEAS_TYPE, $c['id'], $c['owner_staff_id'], 0);
  109. }
  110. } catch (Exception $e) {
  111. Log::error($e->getMessage());
  112. }
  113. }
  114. }
  115. return 'success';
  116. }
  117. /**
  118. * 日程提醒
  119. * @return string
  120. */
  121. public function event()
  122. {
  123. $endDate = date('Y-m-d H:i:s');
  124. $events = Event::where(['status' => 0, 'remind_time' => ['lt', $endDate]])->select();
  125. $endIds = Event::where([
  126. 'status' => ['in', [0, 1]],
  127. 'auto_end' => 1,
  128. 'end_time' => ['lt', $endDate]
  129. ])->column('id');
  130. try {
  131. //日程自动结束
  132. Event::where(['id' => ['in', $endIds]])->update(['status' => 2]);
  133. //日程时间提醒
  134. foreach ($events as $v) {
  135. if (Message::where([
  136. 'relation_type' => Message::EVENT_TYPE,
  137. 'relation_id' => $v['id'],
  138. 'to_staff_id' => $v['staff_id']
  139. ])->count()) {
  140. //已经提醒过了
  141. continue;
  142. }
  143. Message::addMessage(Message::EVENT_TYPE, $v['id'], $v['staff_id'], 0);
  144. }
  145. } catch (Exception $e) {
  146. return $e->getMessage();
  147. }
  148. return 'success';
  149. }
  150. /**
  151. * 打卡定时任务
  152. */
  153. public function attendance()
  154. {
  155. $w = date('w');
  156. $date = [
  157. 1 => 'monday',
  158. 2 => 'tuesday',
  159. 3 => 'wednesday',
  160. 4 => 'thursday',
  161. 5 => 'friday',
  162. 6 => 'saturday',
  163. 0 => 'weekday',
  164. ];
  165. $weekname = $date[$w];
  166. $times = AttendanceTime::where([$weekname => 1])->select();
  167. if (empty($times)) {
  168. return '未设置规则';
  169. }
  170. $row = AttendanceStatisc::where(['time' => date('Y-m-d')])->find();
  171. if (!empty($row)) {
  172. return '规则已生成';
  173. }
  174. $times = collection($times)->toArray();
  175. $rule = AttendanceRule::where([])->find();
  176. $statiscs = AttendanceStatisc::where(['time' => date('Y-m-d', strtotime('-1 day'))])->select();
  177. foreach ($statiscs as $v) {
  178. $update = [];
  179. if (empty($t['clock_in']) && !empty($t['clock_out'])) {//缺卡
  180. $update['clock_in_status'] = 1;
  181. }
  182. if (empty($t['clock_out']) && !empty($t['clock_in'])) {//缺卡
  183. $update['clock_out_status'] = 1;
  184. }
  185. if (empty($t['clock_in']) && empty($t['clock_out'])) {//旷工
  186. $update['clock_in_status'] = 2;
  187. $update['clock_out_status'] = 2;
  188. }
  189. if ($update) {
  190. $statiscModel = new AttendanceStatisc();
  191. $statiscModel->save($update, ['id' => $v['id']]);
  192. }
  193. }
  194. $staff_ids = explode(',', $rule['staff_id']);
  195. $statisc = [];
  196. foreach ($staff_ids as $sid) {
  197. foreach ($times as $t) {
  198. $statisc[] = [
  199. 'staff_id' => $sid,
  200. 'number' => $t['number'],
  201. 'time' => date('Y-m-d'),
  202. 'start_time' => $t['start_time'],
  203. 'end_time' => $t['end_time'],
  204. 'ustart_time' => $t['ustart_time'],
  205. 'uend_time' => $t['uend_time'],
  206. 'dstart_time' => $t['dstart_time'],
  207. 'dend_time' => $t['dend_time'],
  208. 'start_status' => $t['start_status'],
  209. 'end_status' => $t['end_status'],
  210. ];
  211. }
  212. }
  213. $statiscModel = new AttendanceStatisc();
  214. $result = $statiscModel->allowField(true)->saveAll($statisc);
  215. if (empty($result)) {
  216. return '生成规则失败';
  217. }
  218. return '生成规则成功';
  219. }
  220. /*
  221. * 线索池分配
  222. */
  223. public function leadpool(){
  224. if(AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD)){
  225. $leadauto = AdminConfig::getConfigValue('leadauto', AdminConfig::TYPE_LEAD);
  226. $lead_day = AdminConfig::getConfigValue('lead_day', AdminConfig::TYPE_LEAD);
  227. $attendance = AdminConfig::getConfigValue('leadcard', AdminConfig::TYPE_LEAD);
  228. $department = AdminConfig::getConfigValue('department', AdminConfig::TYPE_LEAD);
  229. //开启分配
  230. if($leadauto == 1 && $lead_day>0 && $department){
  231. $leadpool = Leads::where('owner_staff_id is null or owner_staff_id = 0')->order('id desc')->limit(100)->column('id');
  232. if($leadpool){
  233. $department = explode(',',$department);
  234. $staffinfo = array();
  235. foreach($department as $k=>$v){
  236. $staffids = Staff::where('', 'exp', Db::raw('FIND_IN_SET(' . $v . ',group_ids)'))->where(['status'=>1])->column('id');
  237. $staffinfo[] = $staffids;
  238. }
  239. if(!$staffinfo){
  240. return '无数据';
  241. }
  242. $staffinfos =[];
  243. foreach($staffinfo as $k=>$v){
  244. foreach($v as $ks=>$vs){
  245. $staffinfos[] = $vs;
  246. }
  247. }
  248. $staff = array_unique($staffinfos);
  249. foreach($leadpool as $ks=>$vs){
  250. $stafflead =[];
  251. foreach($staff as $k=>$v){
  252. if($attendance == 1){ //打卡
  253. $whereC['staff_id']= $v;
  254. $whereC['createtime'] = array(array('egt',strtotime(date('Y-m-d 00:00:00'))),array('elt',strtotime(date('Y-m-d 23:59:59'))));
  255. $leadcard = Attendance::where($whereC)->find();
  256. if(!$leadcard){//未打卡不分配
  257. continue;
  258. }
  259. }
  260. $wherelead['owner_staff_id'] = $v;
  261. $wherelead['receive_time'] = array(array('egt',strtotime('-'.$lead_day.' days',time())),array('elt',time()));
  262. $lead = Leads::where($wherelead)->count();
  263. $stafflead[] = array(
  264. 'id'=>$v,
  265. 'num'=>$lead
  266. );
  267. }
  268. if($stafflead){
  269. $num_count = array_column($stafflead,'num');//返回数组中指定的一列
  270. array_multisort($num_count,SORT_ASC,$stafflead);
  271. Leads::where(array('id'=>$vs))->update(array('owner_staff_id'=>$stafflead[0]['id'],'receive_time'=>time()));
  272. }
  273. }
  274. }
  275. }
  276. }
  277. return 'success';
  278. }
  279. /**
  280. * 钉钉批量获取客户
  281. */
  282. public function dingcustomer(){
  283. date_default_timezone_set('Asia/Shanghai');
  284. $ding=new Ding();
  285. //获取access_token
  286. $token = $ding->getAccessToken();
  287. if($token->errcode != 0){
  288. $this->error($token->errmsg);
  289. }
  290. $ding=new Ding();
  291. $accessToken = $token->access_token;
  292. $DingStaff = DingStaff::where(array('type'=>0))->select();
  293. if(!$DingStaff){
  294. $this->error('员工为空,请先同步员工为空');
  295. }
  296. foreach($DingStaff as $k=>$v){
  297. if(Session::get($v['user_id']."dingcustomer")){
  298. $startnum = intval(Session::get($v['user_id']."dingcustomer")/2-1);
  299. $endnum = Session::get($v['user_id']."dingcustomer");
  300. }else{
  301. $startnum = 0;
  302. $endnum =100;
  303. }
  304. $customer = $ding->customerBatch($accessToken,$v['user_id'],$startnum,$endnum);
  305. if($customer->errcode != 0 || !$customer->result->values){
  306. continue;
  307. }
  308. foreach($customer->result->values as $ks=>$vs){
  309. $customerFind = DingCustomer::where(array('instance_id'=>$vs->instance_id,'type'=>0))->find();
  310. if($customerFind){
  311. continue;
  312. }
  313. $data = json_decode($vs->data,true);
  314. $instance_id = $vs->instance_id;
  315. $customers = isset($data['customer_name']) ? $data['customer_name'] : '';
  316. $adressinfo = isset($data['address']['extendValue']) ? json_decode($data['address']['extendValue'],true) : '';
  317. $address_detail = '';
  318. $address = '';
  319. if($adressinfo){
  320. $province = isset($adressinfo['province']['name']) ? $adressinfo['province']['name'] : '';
  321. $city = isset($adressinfo['city']['name']) ? $adressinfo['city']['name'] : '';
  322. $district = isset($adressinfo['district']['name']) ? $adressinfo['district']['name'] : '';
  323. $address_detail = isset($adressinfo['detail']['name']) ? $adressinfo['detail']['name'] : '';
  324. $address = $province.$city.$district;
  325. }
  326. $remark = isset($data['TextareaField-K55CWZ2E']) ? $data['TextareaField-K55CWZ2E'] : '';
  327. $source = isset($data['DDSelectField-K2U5GX3B']['value']) ? $data['DDSelectField-K2U5GX3B']['value'] : '';
  328. $owner_staff_id=$vs->permission->owner_userid_list[0];
  329. $create_staff_id=$vs->creator_userid;
  330. $createtime = strtotime($vs->gmt_create);
  331. $updatetime = strtotime($vs->gmt_modified);
  332. $customerData = array(
  333. 'instance_id'=>$instance_id,
  334. 'user_id'=>$create_staff_id,
  335. 'name'=>$customers,
  336. 'address'=>$address,
  337. 'address_detail'=>$address_detail,
  338. 'source'=>$source,
  339. 'remark'=>$remark,
  340. 'owner_staff_id'=>$owner_staff_id,
  341. 'create_staff_id'=>$create_staff_id,
  342. 'createtime'=>$createtime,
  343. 'updatetime'=>$updatetime,
  344. );
  345. DingCustomer::create($customerData);
  346. }
  347. if(Session::get($v['user_id']."dingcustomer")){
  348. Session::set($v['user_id']."dingcustomer", 100*2);
  349. }else{
  350. Session::set($v['user_id']."dingcustomer", 100);
  351. }
  352. }
  353. $this->success('同步成功');
  354. }
  355. /**
  356. * 钉钉批量获取联系人
  357. */
  358. public function dingcontacts(){
  359. date_default_timezone_set('Asia/Shanghai');
  360. $ding=new Ding();
  361. //获取access_token
  362. $token = $ding->getAccessToken();
  363. if($token->errcode != 0){
  364. $this->error($token->errmsg);
  365. }
  366. $ding=new Ding();
  367. $accessToken = $token->access_token;
  368. $DingStaff = DingStaff::where(array('type'=>0))->select();
  369. if(!$DingStaff){
  370. $this->error('员工为空,请先同步员工为空');
  371. }
  372. foreach($DingStaff as $k=>$v){
  373. if(Session::get($v['user_id']."dingcontacts")){
  374. $startnum = intval(Session::get($v['user_id']."dingcontacts")/2-1);
  375. $endnum = Session::get($v['user_id']."dingcontacts");
  376. }else{
  377. $startnum = 0;
  378. $endnum =100;
  379. }
  380. $customer = $ding->contactsBatch($accessToken,$v['user_id'],$startnum,$endnum);
  381. if($customer->errcode != 0 || !$customer->result->values){
  382. continue;
  383. }
  384. foreach($customer->result->values as $ks=>$vs){
  385. $customerFind = DingContacts::where(array('instance_id'=>$vs->instance_id))->find();
  386. if($customerFind){
  387. continue;
  388. }
  389. $data = json_decode($vs->data,true);
  390. $contact_related_customer = json_decode($data['contact_related_customer']['extendValue'],true);
  391. $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
  392. if(!$instanceId){
  393. continue;
  394. }
  395. $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
  396. if(!$customerId){
  397. continue;
  398. }
  399. $instance_id = $vs->instance_id;
  400. $contact_name = isset($data['contact_name']) ? $data['contact_name'] : '';
  401. $post = isset($data['contact_position']['extendValue']) ? json_decode($data['contact_position']['extendValue'],true)[0]['label'] : '';
  402. $email = isset($data['TextField-K55DPXC9']) ? $data['TextField-K55DPXC9'] : '';
  403. $mobile = isset($data['contact_phone']['value']) ? $data['contact_phone']['value'] : '';
  404. $remark = isset($data['TextareaField-K2UG1B59']) ? $data['TextareaField-K2UG1B59'] : '';
  405. $owner_staff_id=$vs->permission->owner_userid_list[0];
  406. $create_staff_id=$vs->creator_userid;
  407. $createtime = strtotime($vs->gmt_create);
  408. $updatetime = strtotime($vs->gmt_modified);
  409. $customerData = array(
  410. 'instance_id'=>$instance_id,
  411. 'customer_id'=>$customerId,
  412. 'name'=>$contact_name,
  413. 'post'=>$post,
  414. 'email'=>$email,
  415. 'mobile'=>$mobile,
  416. 'remarks'=>$remark,
  417. 'owner_staff_id'=>$owner_staff_id,
  418. 'create_staff_id'=>$create_staff_id,
  419. 'createtime'=>$createtime,
  420. 'updatetime'=>$updatetime,
  421. );
  422. DingContacts::create($customerData);
  423. }
  424. if(Session::get($v['user_id']."dingcontacts")){
  425. Session::set($v['user_id']."dingcontacts", 100*2);
  426. }else{
  427. Session::set($v['user_id']."dingcontacts", 100);
  428. }
  429. }
  430. $this->success('同步成功');
  431. }
  432. /**
  433. * 钉钉批量获取跟进记录
  434. */
  435. public function dingrecord(){
  436. date_default_timezone_set('Asia/Shanghai');
  437. $ding=new Ding();
  438. //获取access_token
  439. $token = $ding->getAccessToken();
  440. if($token->errcode != 0){
  441. $this->error($token->errmsg);
  442. }
  443. $ding=new Ding();
  444. $accessToken = $token->access_token;
  445. $DingStaff = DingStaff::select();
  446. if(!$DingStaff){
  447. $this->error('员工为空,请先同步员工为空');
  448. }
  449. foreach($DingStaff as $k=>$v){
  450. if(Session::get($v['user_id']."dingrecord")){
  451. $startnum = intval(Session::get($v['user_id']."dingrecord")/2-1);
  452. $endnum = Session::get($v['user_id']."dingrecord");
  453. }else{
  454. $startnum = 0;
  455. $endnum =100;
  456. }
  457. $customer = $ding->recordBatch($accessToken,$v['user_id'],$startnum,$endnum);
  458. if($customer->errcode != 0 || !$customer->result->values){
  459. continue;
  460. }
  461. foreach($customer->result->values as $ks=>$vs){
  462. $customerFind = DingRecord::where(array('instance_id'=>$vs->instance_id))->find();
  463. if($customerFind){
  464. continue;
  465. }
  466. $data = json_decode($vs->data,true);
  467. $contact_related_customer = json_decode($data['follow_record_related_customer']['extendValue'],true);
  468. $instanceId = isset($contact_related_customer['list'][0]['instanceId']) ? $contact_related_customer['list'][0]['instanceId'] : '';
  469. if(!$instanceId){
  470. continue;
  471. }
  472. $customerId = DingCustomer::where(array('instance_id'=>$instanceId))->value('id');
  473. if(!$customerId){
  474. continue;
  475. }
  476. $instance_id = $vs->instance_id;
  477. $content = isset($data['TextareaField-K2U5UJAF']) ? $data['TextareaField-K2U5UJAF'] : '';
  478. $create_staff_id=$vs->creator_userid;
  479. $createtime = strtotime($vs->gmt_create);
  480. $updatetime = strtotime($vs->gmt_modified);
  481. $customerData = array(
  482. 'instance_id'=>$instance_id,
  483. 'customer_id'=>$customerId,
  484. 'content'=>$content,
  485. 'create_staff_id'=>$create_staff_id,
  486. 'createtime'=>$createtime,
  487. 'updatetime'=>$updatetime,
  488. );
  489. DingRecord::create($customerData);
  490. }
  491. if(Session::get($v['user_id']."dingrecord")){
  492. Session::set($v['user_id']."dingrecord", 100*2);
  493. }else{
  494. Session::set($v['user_id']."dingrecord", 100);
  495. }
  496. }
  497. $this->success('同步成功');
  498. }
  499. /**
  500. * 企业微信批量获取客户
  501. */
  502. public function wxcustomer(){
  503. $this->corpid =AdminConfig::where(array('field'=>'corpid'))->value('value');
  504. $corpsecret=AdminConfig::where(array('field'=>'corpsecret'))->value('value');
  505. $url ='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$this->corpid.'&corpsecret='.$corpsecret;
  506. $token = $this->http_get($url);
  507. $token = json_decode($token,true);
  508. if($token['errcode'] != 0){
  509. $this->error($token['errmsg']);
  510. }
  511. $DingStaff = DingStaff::where(array('type'=>1))->limit(100)->select();
  512. if(!$DingStaff){
  513. $this->error('员工为空,请先同步员工为空');
  514. }
  515. $staffUser = array();
  516. foreach($DingStaff as $k=>$v){
  517. $staffUser[] = $v['user_id'];
  518. }
  519. $user = array(
  520. 'userid_list'=>$staffUser,
  521. 'cursor'=>Session::get("wxcustomer"),
  522. 'limit'=>100
  523. );
  524. $url ='https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token='.$token['access_token'];
  525. $customer = $this->http_post($url,json_encode($user));
  526. $customer = json_decode($customer,true);
  527. if($customer['errcode'] != 0){
  528. $this->error($customer['errmsg']);
  529. }
  530. Session::set("wxcustomer", $customer['next_cursor']);
  531. foreach($customer['external_contact_list'] as $ks=>$vs){
  532. $customerFind = DingCustomer::where(array('instance_id'=>$vs['external_contact']['external_userid']))->find();
  533. if($customerFind){
  534. continue;
  535. }
  536. $data = $vs;
  537. $instance_id = isset($data['external_contact']['external_userid']) ? $data['external_contact']['external_userid'] : '';
  538. $customerName = isset($data['external_contact']['name']) ? addslashes(filter_Emoji($data['external_contact']['name'])) : '';
  539. $owner_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
  540. $create_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
  541. $createtime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';
  542. $updatetime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';
  543. $customerData = array(
  544. 'type' => 1,
  545. 'instance_id'=>$instance_id,
  546. 'user_id'=>$create_staff_id,
  547. 'name'=>$customerName,
  548. 'owner_staff_id'=>$owner_staff_id,
  549. 'create_staff_id'=>$create_staff_id,
  550. 'createtime'=>$createtime,
  551. 'updatetime'=>$updatetime,
  552. );
  553. $customers = DingCustomer::create($customerData);
  554. $customerId = DingCustomer::getLastInsID();
  555. //同步联系人
  556. $contactFind = DingContacts::where(array('instance_id'=>$instance_id))->find();
  557. if($contactFind){
  558. DingContacts::where(array('id'=>$contactFind['id']))->update(array('customer_id' =>$customerId));
  559. continue;
  560. }
  561. $contactData = array(
  562. 'type' =>1,
  563. 'instance_id' =>$instance_id,
  564. 'customer_id' =>$customerId,
  565. 'name' =>$customerName,
  566. 'mobile' =>isset($data['follow_info']['remark_mobiles'][0]) ? $data['follow_info']['remark_mobiles'][0] : '',
  567. 'create_staff_id' =>$owner_staff_id,
  568. 'owner_staff_id' =>$create_staff_id,
  569. );
  570. DingContacts::create($contactData);
  571. }
  572. $this->success('同步成功');
  573. }
  574. /**
  575. * curl请求
  576. */
  577. private function http_get($url){
  578. $oCurl = curl_init();
  579. if(stripos($url,"https://")!==FALSE){
  580. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  581. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  582. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  583. }
  584. curl_setopt($oCurl, CURLOPT_URL, $url);
  585. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  586. $sContent = curl_exec($oCurl);
  587. $aStatus = curl_getinfo($oCurl);
  588. curl_close($oCurl);
  589. if(intval($aStatus["http_code"])==200){
  590. return $sContent;
  591. }else{
  592. return false;
  593. }
  594. }
  595. /**
  596. * curl请求
  597. */
  598. private function http_post($url,$param,$post_file=false){
  599. $oCurl = curl_init();
  600. if(stripos($url,"https://")!==FALSE){
  601. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  602. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  603. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  604. }
  605. if (is_string($param) || $post_file) {
  606. $strPOST = $param;
  607. } else {
  608. $aPOST = array();
  609. foreach($param as $key=>$val){
  610. $aPOST[] = $key."=".urlencode($val);
  611. }
  612. $strPOST = join("&", $aPOST);
  613. }
  614. curl_setopt($oCurl, CURLOPT_URL, $url);
  615. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  616. curl_setopt($oCurl, CURLOPT_POST,true);
  617. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  618. $sContent = curl_exec($oCurl);
  619. $aStatus = curl_getinfo($oCurl);
  620. curl_close($oCurl);
  621. if(intval($aStatus["http_code"])==200){
  622. return $sContent;
  623. }else{
  624. return false;
  625. }
  626. }
  627. public function sycn_openid()
  628. {
  629. $wechat2 = new Wechat('wxOfficialAccount');
  630. $batch = $wechat2->getUsers();
  631. if (empty($batch['data'])) {
  632. return '微信配置有误!';
  633. }
  634. $openid = $batch['data']['openid'];
  635. $model = new Staff();
  636. $old_openid = $model->where([])->column('openid');
  637. foreach ($openid as $k => $v) {
  638. if (in_array($v, $old_openid)) {
  639. unset($openid[$k]);
  640. }
  641. }
  642. $openid = array_values($openid);
  643. $openids = array_chunk($openid, 100);
  644. $weopen = new WechatOpenid();
  645. foreach ($openids as $o_ids) {
  646. $insertAll = [];
  647. $result = $wechat2->getBatchget($o_ids);
  648. if (empty($result['user_info_list'])) {
  649. return '微信配置有误!';
  650. }
  651. foreach ($result['user_info_list'] as $index => $item) {
  652. $unionid = $weopen->where(['unionid'=>$item['unionid']])->find();
  653. if(!$unionid){
  654. if (isset($item['unionid'])) {
  655. $model->where(['unionid'=>$item['unionid']])->update(['wx_openid'=>$item['openid']]);
  656. $insertAll[] = [
  657. 'openid' => $item['openid'],
  658. 'unionid' => $item['unionid']
  659. ];
  660. }
  661. }
  662. }
  663. $weopen->insertAll($insertAll);
  664. }
  665. return 'success';
  666. }
  667. }