发布时间:2023-03-05
先进行验证代码,
然后直接 加 外部联系人 等相关事件回调处理就行....
验证,完成就可以不调用这个方法了
function demo(){
$sVerifyMsgSig = $_GET['msg_signature'];
$sVerifyTimeStamp = $_GET['timestamp'];
$sVerifyNonce = $_GET['nonce'];
$sVerifyEchoStr = $_GET['echostr'];
// 需要返回的明文
$sEchoStr = "自定义";
$wxcpt = new \WXBizMsgCrypt('xxxxxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxxxx');
$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
if ($errCode == 0) {
// 验证URL成功,将sEchoStr返回
return $sEchoStr;
} else {
print("ERR: " . $errCode . "\n\n");
}
}1.https 记得加
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
2. json格式记得加header请求头
整体代码
获取学员列表中信息,同步外部联系人标签,备注等,消息推送
<?php
apimian();
function apimian(){
//回调开启
include_once "WXBizMsgCrypt.php";
$encodingAesKey = "xxxxxxx";
$token = "xxxxxxx";
$corpId = "xxxxxxx";
date_default_timezone_set('PRC');
$sReqMsgSig = isset($_GET['msg_signature'])?$_GET['msg_signature']:'';
$sReqTimeStamp = isset($_GET['timestamp'])?$_GET['timestamp']:'';
$sReqNonce = isset($_GET['nonce'])?$_GET['nonce']:'';
$sReqData = file_get_contents("php://input");
$params = $_GET;
$params['xmlContent'] = $sReqData; //post的xml数据
$sMsg = '';
$wxcpt = new WXBizMsgCrypt('企微的信息', '企微的', '企微的');
$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
if ($errCode == 0) {
$msg_arr = json_decode(json_encode(simplexml_load_string($sMsg,"SimpleXMLElement", LIBXML_NOCDATA)),true);
$type = isset($msg_arr['ChangeType'])?$msg_arr['ChangeType']:'';
if ($type != 'add_external_contact') {
return;
}
//外部联系人的userid
$external_userid = isset($msg_arr['ExternalUserID'])?$msg_arr['ExternalUserID']:'';
//客服userid
$userid = isset($msg_arr['UserID'])?$msg_arr['UserID']:'';
//应用id
$to_user_name = isset($msg_arr['ToUserName'])?$msg_arr['ToUserName']:'';
//改变类型
$welcome_code = isset($msg_arr['WelcomeCode'])?$msg_arr['WelcomeCode']:'';
$access_token = accessToken();
$unionid = unionid($external_userid,$access_token);
if ($unionid == 40014) {
$access_token = accessToken();
$unionid = unionid($external_userid,$access_token);
}
if ($unionid == '') {
putMark($userid.'的--'.$external_userid.'--无学员信息');
} else {
// 自动备注信息,手机号
$used_data = used_data($unionid,$access_token,$userid,$external_userid,$welcome_code);
if ($user_data != 0) {
putMark($userid.'的--'.$external_userid.'添加备注失败');
return;
}
}
return;
} else {
$time = date('Y-m-d h:i:s',time());
$data = $time.$sMsg;
$address = 'externalCallbackEvent_params.log';
file_put_contents($address,"--ERR: ".$data. $errCode . "\n\n",FILE_APPEND);
return "ERR: " . $errCode.$sMsg;
}
}
function unionid($external_userid,$access_token){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$access_token.'&external_userid='.$external_userid;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
// 这里判断一下失效
if ($output['errcode'] == 40014) {
return 40014;
}
$unionid = isset($output['external_contact']['unionid'])?$output['external_contact']['unionid']:'';
// putMark('调试信息'.$url.'--'.$output);
return $unionid;
}
function used_data($unionid,$access_token,$userid,$external_userid,$welcome_code){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$url = '学员的api接口'.$unionid;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
$user_data = [];
if ($output['data']['member_info'] != null ) {
$user_data['realname'] = $output['data']['member_info']['realname']; // 名称
$user_data['phone'] = $output['data']['member_info']['phone']; // 手机
$user_data['grade_name'] = $output['data']['member_info']['grade_name']; // 年级
$user_data['major_name'] = $output['data']['member_info']['major_name']; // 专业
$user_data['school_name'] = $output['data']['member_info']['school_name']; // 学校
$subjects = $output['data']['subjects']; // 科目
$course_name = $output['data']['course_name']; // 班型
// 加备注
$post_userremark = post_userremark($access_token,$userid,$external_userid,$user_data['realname'],$user_data['phone'],$user_data['grade_name'],$user_data['major_name'],$user_data['school_name'],$course_name);
// 加标签
// 数据库连接
$db=new mysqli('localhost','xxxxxxx','xxxxxxx','xxxxxxxx');
if(mysqli_connect_error()){
putMark('Could not connect to database.');
exit;
}
$result = $db->query("SELECT type FROM zf_kefu where name = '".$userid."'");
$row=$result->fetch_row();
if (implode('',$row) == '客服') {
// 消息推送
$sen = send_welcome_msg($access_token,$welcome_code,$userid,$user_data['phone']);
}
$tags = [];
foreach ($subjects as $tagi) {
$name = $tagi['name'];
$result = $db->query("SELECT qun_etid FROM zf_qun where province_name = '".$name."' and yi_num < recruit_num and yi_num < recruit_num and nianji = '".$user_data['grade_name']."' limit 1");
$row=$result->fetch_row();
if ($row) {
$tags[] = implode('',$row);
}
}
if (strstr($course_name,'智学') != '') {
$result = $db->query("SELECT qun_etid FROM zf_qun where province_name = '".$user_data['major_name']."' and province_code = '答疑' and yi_num < recruit_num limit 1");
$row = $result->fetch_row();
if ($row) {
$tags[] = implode('',$row);
}
}
$result = $db->query("SELECT qun_etid FROM zf_qun where province_name = '".$user_data['major_name']."' and province_code = '交流' and yi_num < recruit_num limit 1");
$row = $result->fetch_row();
if ($row) {
$tags[] = implode('',$row);
}
putMark('-- 执行$tags'.$user_data['phone'].implode('----',$tags));
$res_tag = newsTag($access_token,$userid,$external_userid,$tags);
return $post_userremark;
} else {
$user_data = '1';
putMark('-- 获取学员api问题---'.$url.'---'.$unionid);
return $user_data;
}
}
// 修改备注
function post_userremark($access_token,$userid,$external_userid,$realname,$phone,$grade_name,$major_name,$school_name,$course_name){
$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token='.$access_token;
$data ='{"userid":"'.$userid.'","external_userid":"'.$external_userid.'","remark":"'.$grade_name.'-'.$realname.'","description":"'.$major_name.'--'.$course_name.'--'.$school_name.'","remark_mobiles":"'.$phone.'"}';
$ch = curl_init();
$headers = array(
"Content-type: application/json;charset='utf-8'",
"Accept: application/json",
"Cache-Control: no-cache",
"Pragma: no-cache",
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
curl_close($ch);
$ret = json_decode($ret,true);
putMark('-- 修改备注情况'.$phone.'--'.implode('',$ret));
return $ret['errcode'];
}
// 标签
function newsTag($access_token,$userid,$external_userid,$tags){
$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token='.$access_token;
$data = '{
"userid":"'.$userid.'",
"external_userid":"'.$external_userid.'",
"add_tag":["'.implode('","',$tags).'"]
}';
$ret = postJson($url,$data);;
putMark('+标签'.$url.$external_userid.'--'.implode('',$ret));
if ($ret['errcode'] == 0) {
$db=new mysqli('xxxxxxx','xxxxxxxxx','xxxxxxx','xxxxxxxxx');
if(mysqli_connect_error()){
putMark('Could not connect to database.');
exit;
}
foreach ($tags as $tagi) {
$db->query("update zf_qun set yi_num = yi_num+1 where qun_etid = '".$tagi."'");
}
}
return $ret['errcode'];
}
// 消息推送
function send_welcome_msg($access_token,$welcome_code,$userid,$phone){
// 查询 匹配的督学老师
$db=new mysqli('xxxxxxx','xxxxxxxxx','xxxxxxxx','xxxxxxxxx');
if(mysqli_connect_error()){
putMark('Could not connect to database.');
exit;
}
// 手机号,查询对应的值
$result2 = $db->query("SELECT teacher FROM zf_student_teacher where student_phone = '".$phone."' LIMIT 1");
$row = $result2->fetch_row();
if ($row) {
$imgurl = implode('',$row);
} else {
// 查询 是否已被加重置
$result = $db->query("SELECT url FROM zf_kefu where ispost = 0 and type = '教务' limit 1");
$row=$result->fetch_row();
if ($row) {
$imgurl = implode('',$row);
} else {
$db->query("update zf_kefu set ispost = 0 where type = '教务'");
$result = $db->query("SELECT url FROM zf_kefu where ispost = 0 and type = '教务' limit 1");
$row=$result->fetch_row();
$imgurl = implode('',$row);
}
}
$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token='.$access_token;
$data = '{
"welcome_code":"'.$welcome_code.'",
"text": {
"content": "xxxxxxxxxxx。"
},
"attachments": [{
"msgtype": "image",
"image": {
"pic_url":"'.$imgurl.'"
}
},
]
}';
$ret = postJson($url,$data);;
putMark('消息推送'.$external_userid.'--'.implode('',$ret));
// 更新该字段
$db->query("update zf_kefu set ispost = 1 where url = '".$imgurl."'");
return $ret['errcode'];
}
// 获取成员的二维码
function userid_img($access_token,$userid){
$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&userid='.$userid;
$res = getJson($url);
putMark('img'.'--'.implode('',$res));
$qr_code = $res['qr_code'];
return $qr_code;
}
function accessToken() {
$tokenFile = "access_token.txt";//緩存文件名
$data = json_decode(file_get_contents($tokenFile));
if ($data->expires_in < time() == 1 or !$data->expires_in) {
$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxxxxxxxxxxxxxxx&corpsecret=xxxxxxxxxxxxxxxxxxxxxxx';
$res = getJson($url);
$access_token = $res['access_token'];
if($access_token) {
$data = [];
$data['expires_in'] = time() + 7200;
$data['access_token'] = $access_token;
$fp = fopen($tokenFile, "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
}
else {
$access_token = $data->access_token;
}
return $access_token;
}
function getJson($url){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
function postJson($url,$data){
$ch = curl_init();
$headers = array(
"Content-type: application/json;charset='utf-8'",
"Accept: application/json",
"Cache-Control: no-cache",
"Pragma: no-cache",
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
curl_close($ch);
$ret = json_decode($ret,true);
return $ret;
}
function putMark($params){
# 记录入参
$time = date('Y-m-d h:i:s',time());
// $paramsStr = json_encode($params,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
$data = $time.'---'.$params;
$address = 'log.log';
file_put_contents($address,$data."\r\n",FILE_APPEND);
}
发表评论
留言: