Skip to main content

企业微信通讯录同步

[TOC]

通讯录同步

引言

通讯录同步,官方通过设置回调url可以接收通讯录成员和部门的变动信息。标签增加删除并不给回调url推送,只有标签内成员发送变动才会推送。 所以我也没有同步标签。

步骤

1. 介绍

我接口版本文件里,每个文件都是一个应用 我有一个基类ContactsController.php 这个文件夹的位置是G:\WWW\wework\app\Http\Controllers\V1\Contacts\ContactsController.php
后面的文件位置根据psr-4规范自己推吧

基类

<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/11
* Time: 15:02
*/

namespace App\Http\Controllers\V1\Contacts;

use App\Http\Controllers\V1\Controller;
use App\Traits\WorkConfig;

class ContactsController extends Controller
{
use WorkConfig;

public function __construct()
{
$this->corpid = config('wework.CORP_ID');
$this->secret = config('wework.CONTACT_SYNC_SECRET');
$url = base_path()."/app/SDK/weworkapi/api/src/CorpAPI.class.php";
$this->token = config('wework.CONTACT_TOKEN');
$this->encodingAESKey = config('wework.CONTACT_EncodingAESKey');

include_once (str_ireplace('\\','/',$url));
$this->api = new \CorpAPI($this->corpid, $this->secret);
}
}

trait类

<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/11
* Time: 14:02
*/
namespace App\Traits;

trait WorkConfig
{
protected $api;
protected $corpid;
protected $appid;
protected $agentid;
protected $redirect_uri;
protected $token;
protected $encodingAESKey;
protected $key;
}

2. 设置回调url

CallBackController.php 文件

<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/11
* Time: 10:48
*/

namespace App\Http\Controllers\V1\Contacts;

//消息回调
use App\Http\Controllers\V1\Controller;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\User;

class CallBackController extends ContactsController
{


//
public function callBack(Request $request)
{
include_once base_path()."/app/SDK/weworkapi/callback/WXBizMsgCrypt.php";
Log::info('返回值',$request->input());

// $sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature");
$sMsgSignature = $request->input('msg_signature');
// $sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp");
$sTimeStamp = $request->input('timestamp');
// $sVerifyNonce = HttpUtils.ParseUrl("nonce");
$sNonce = $request->input('nonce');
// $sVerifyEchoStr = HttpUtils.ParseUrl("echostr");
$sReplyEchoStr = $request->input('echostr');

$wxcpt = new \WXBizMsgCrypt($this->token,$this->encodingAESKey , $this->corpid);

if (!empty($sReplyEchoStr))
{
// 验证回调地址
// 需要返回的明文
$sEchoStr = "";

$errCode = $wxcpt->VerifyURL($sMsgSignature, $sTimeStamp, $sNonce, $sReplyEchoStr, $sEchoStr);
if ($errCode == 0) {
return $sEchoStr;
} else {
print("ERR: " . $errCode . "\n\n");
}
}else{
// 接受到的XML
$sReqData = file_get_contents('php://input');
$sMsg = ""; // 解析之后的明文
//检验消息的真实性,并且获取解密后的明文
$errCode = $wxcpt->DecryptMsg($sMsgSignature, $sTimeStamp, $sNonce, $sReqData, $sMsg);
if ($errCode == 0) {

$sMsg = Xml2Array($sMsg);

// 解密成功,sMsg即为xml格式的明文
Log::info('解密成功',$sMsg);
// TODO: 对明文的处理

if ($sMsg["MsgType"] == 'event')
{
if($sMsg["Event"] == 'change_contact')
{
if (strpos($sMsg['ChangeType'],'user'))
{
User::work_change($sMsg);
}
elseif (strpos($sMsg['ChangeType'],'party'))
{
Department::work_change($sMsg);
}
elseif (strpos($sMsg['ChangeType'],'party'))
{
Department::work_change($sMsg);
}

}
}

} else {
Log::error('XML解密失败:'.$errCode);
print("ERR: " . $errCode . "\n\n");
//exit(-1);
}

}

}
}

数据库设置

1. 成员
<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/5
* Time: 15:08
*/

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class User extends Model
{
protected $table = 'user';
protected $primaryKey = 'userid';

protected $fillable = ['userid','name','alias','mobile','department','order','position','gender','email','telephone','is_leader_in_dept','avatar_mediaid','enable','extattr','to_invite','external_profile','external_position','address','avatar','thumb_avatar','status','qr_code'];



public static function work_change($sMsg)
{
Log::info($sMsg);
if ($sMsg['ChangeType'] == 'update_user')
{
return self::work_update($sMsg);
}
else if ($sMsg['ChangeType'] == 'create_user')
{
return self::work_create($sMsg);
}
else if ($sMsg['ChangeType'] == 'delete_user')
{
return self::work_delete($sMsg);
}

}

//新增
public static function work_create($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::create($data);
}

//更新
public static function work_update($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::where('userid',$data['userid'])->update($data);
}

//删除
public static function work_delete($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::where('userid',$data['userid'])->delete();
}


//修改企业微信返回的数据的命名
public static function work_callback_rewrite($sMsg)
{
// unset($sMsg['ToUserName']);
// unset($sMsg['FromUserName']);
// unset($sMsg['MsgType']);
// unset($sMsg['Event']);
// unset($sMsg['ChangeType']);
// unset($sMsg['CreateTime']);
$data = array();
foreach ($sMsg as $key=>$row)
{
switch ($key)
{
case 'UserID':
$data['userid'] = $row;
break;
case 'Name':
$data['name'] = $row;
break;
case 'Department':
$data['department'] = ArrToString($row);
break;
case 'IsLeaderInDept':
$data['is_leader_in_dept'] = ArrToString($row);
break;
case 'Mobile':
$data['mobile'] = $row;
break;
case 'Position':
$data['position'] = $row;
break;
case 'Gender':
$data['gender'] = $row;
break;
case 'Email':
$data['email'] = $row;
break;
case 'Status':
$data['status'] = $row;
break;
case 'Avatar':
$data['avatar'] = $row;
break;
case 'Alias':
$data['alias'] = $row;
break;
case 'Telephone':
$data['telephone'] = $row;
break;
case 'Address':
$data['address'] = $row;
break;
case 'ExtAttr':
$data['extattr'] = json_encode($row);
break;
}
}

return $data;
}
}
2.部门
<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/5
* Time: 15:08
*/

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class Department extends Model
{
protected $table = 'department';
protected $primaryKey = 'id';

protected $fillable = ['id','name','name_en','parentid','order','created_at','updated_at'];



public static function work_change($sMsg)
{
Log::info($sMsg);
if ($sMsg['ChangeType'] == 'update_party')
{
return self::work_update($sMsg);
}
else if ($sMsg['ChangeType'] == 'create_party')
{
return self::work_create($sMsg);
}
else if ($sMsg['ChangeType'] == 'delete_party')
{
return self::work_delete($sMsg);
}

}

//新增
public static function work_create($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::create($data);
}

//更新
public static function work_update($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::where('id',$data['id'])->update($data);
}

//删除
public static function work_delete($sMsg)
{
$data = self::work_callback_rewrite($sMsg);
return self::where('id',$data['id'])->delete();
}


//修改企业微信返回的数据的命名
public static function work_callback_rewrite($sMsg)
{
// unset($sMsg['ToUserName']);
// unset($sMsg['FromUserName']);
// unset($sMsg['MsgType']);
// unset($sMsg['Event']);
// unset($sMsg['ChangeType']);
// unset($sMsg['CreateTime']);
$data = array();
foreach ($sMsg as $key=>$row)
{
switch ($key)
{
case 'Id':
$data['id'] = $row;
break;
case 'Name':
$data['name'] = $row;
break;
case 'ParentId':
$data['parentid'] = $row;
break;
case 'Order':
$data['order'] = $row;
break;
}
}

return $data;
}

}

3.同步成员

UsersController.php 文件

<?php

namespace App\Http\Controllers\V1\Contacts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UsersController extends ContactsController
{
/**
* Create a new controller instance.
*
* @return void
*/


//同步数据用户保存进数据库
public function sync(){

//获取所有用户
$user_list = $this->api->UserSimpleList(1,1);
foreach ($user_list as $user)
{
User::updateOrCreate(['userid' => $user->userid], saveDateToDb(Object2Array($user)));
}
return $user_list;
}

/**
* 获取用户详情
* @param Request $request
* @return false|string
* @throws \Illuminate\Validation\ValidationException
*/
public function UserGet(Request $request)
{
$this->validate($request, [
'userid' => 'required'
]);
$userid = $request->input('userid');
$user = $this->api->UserGet($userid);
return $this->jsonSuccessData($user);
}

//创建成员
public function UserCreate(Request $request)
{
$request_user = $request->all();
include_once base_path()."/app/SDK/weworkapi/api/datastructure/User.class.php";
$user = new \User();

foreach ($request_user as $key=>$item)
{
if ($key =='department' )
{
$user->$key = explode(',',$item);
}else{
$user->$key = $item;
}
}

$result = $this->api->UserCreate($user);
if (empty($result))
{
\App\Models\User::insert($request_user);
}

return $this->jsonSuccessData($result);
}


//更新成员
public function UserUpdate(Request $request)
{
$request_user = $request->all();
include_once base_path()."/app/SDK/weworkapi/api/datastructure/User.class.php";
$user = new \User();

foreach ($request_user as $key=>$item)
{
if ($key =='department' )
{
$user->$key = explode(',',$item);
}else{
$user->$key = $item;
}
}
$result = $this->api->UserUpdate($user);
if (empty($result))
{
\App\Models\User::where('userid',$request_user['userid'])->update($request_user);
}

return $this->jsonSuccessData($result);
}

//删除成员
public function UserDelete(Request $request)
{
$userid = $request->input('userid');

$result = $this->api->UserDelete($userid);
if (empty($result))
{
\App\Models\User::where('userid',$userid)->delete();
}
return $this->jsonSuccessData($result);
}


//userid与openid互换
public function convert_to_openid($userid)
{
$openid = null;
$this->api->UserId2OpenId($userid,$openid);
return $openid;
}



}

4.同步部门

DepartmentController.php 文件

<?php
/**
* Created by PhpStorm.
* User: 清行
* Date: 2020/3/5
* Time: 16:16
*/

namespace App\Http\Controllers\V1\Contacts;

use App\Models\Department;
use Illuminate\Http\Request;

class DepartmentController extends ContactsController
{

//同步部门数据保存进数据库
public function sync(){
//获取部门列表
$list = $this->api->DepartmentList();
foreach ($list as $vo)
{
Department::updateOrCreate(['id' => $vo->id],(array)$vo);
}
return $list;
}

/**
* 获取部门详情
* @param Request $request
* @return false|string
* @throws \Illuminate\Validation\ValidationException
*/
public function DepartmentList(Request $request)
{
$this->validate($request, [
'id' => 'required'
]);
$id = $request->input('id');
$user = $this->api->DepartmentList($id);
return $this->jsonSuccessData($user);
}

//创建部门
public function DepartmentCreate(Request $request)
{
$request_data = $request->all();
include_once base_path()."/app/SDK/weworkapi/api/datastructure/Department.class.php";
$department = new \Department();

foreach ($request_data as $key=>$item)
{
if ($key == 'parentid' || $key == 'id' )
{
$department->$key = (int)$item;
}else{
$department->$key = $item;
}
}
$result = $this->api->DepartmentCreate($department);
if (is_int($result) && $result>0)
{
$request_data['id'] = $result;
\App\Models\Department::insert($request_data);
}
return $this->jsonSuccessData($result);
}


//更新部门
public function DepartmentUpdate(Request $request)
{
$request_data = $request->all();
include_once base_path()."/app/SDK/weworkapi/api/datastructure/Department.class.php";
$department = new \Department();

foreach ($request_data as $key=>$item)
{
if ($key == 'parentid' || $key == 'id' )
{
$department->$key = (int)$item;
}else{
$department->$key = $item;
}
}
$result = $this->api->DepartmentUpdate($department);

if (empty($result))
{
\App\Models\Department::where('id',$request_data['id'])->update($request_data);
}

return $this->jsonSuccessData($result);
}

//删除部门
public function DepartmentDelete(Request $request)
{
$id = (int)$request->input('id');

$result = $this->api->DepartmentDelete($id);
if (empty($result))
{
\App\Models\Department::where('id',$id)->delete();
}
return $this->jsonSuccessData($result);
}

}