jstang博客

时间:

  • 首页
  • zblog作品
  • 前端笔记
  • python
  • seo
  • cms
    • zblog
    • 帝国cms
  • 杂记

当前位置:

  • 首页
  • 前端笔记

php 企业微信外部联系人回调

发布时间:2023-03-05

作者: jstang

1461 0

先进行验证代码,

然后直接 加 外部联系人  等相关事件回调处理就行....


验证,完成就可以不调用这个方法了

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);
}


    标签:php 企业微信

    文章版权及转载声明

    作者:jstang本文地址:https://jstang.cn/post/228.html发布于2023-03-05
    文章转载或复制请以超链接形式并注明出处jstang博客

    • 上一篇 :css 固定宽高后图片裁剪
    • 下一篇 :微信公众号验证及被动回复事件

    同类推荐

    发表评论

    留言:dddxzxx

    最新文章

    windows定时访问脚本bat

    windows定时访问脚本bat

    @echo off:loopREM 获取当前小时(24小时制...

    • 55
    • 0
    宝塔瘦身,清理硬盘

    宝塔瘦身,清理硬盘

    1  /var/log/journal/...

    • 143
    • 0
    世界知识现在掌握在每个人的手掌中

    世界知识现在掌握在每个人的手掌中

    世界知识现在掌握在每个人的手掌中...

    • 228
    • 0
    想法--执行

    想法--执行

    未来属于那些有想法、还能动手去做的人。创办一家公司并不真的需...

    • 238
    • 0
    老张站群-单程序N域名站群插件演示

    老张站群-单程序N域名站群插件演示

    操作演示视频部分https://www.bilibili.c...

    • 739
    • 0

    热门排行

    css实现超出固定长度的部分以省略号显示

    css实现超出固定长度的部分以省略号显示

    1.一行中超出固定长度的部分以省略号显示#div1{&n...

    • 40453
    • 1
    老张站群-站群教程

    老张站群-站群教程

    注意 进行 超时设置 以防止50x PS : 源站...

    • 2684
    • 0
    python线程池

    python线程池

    ...

    • 2375
    • 0
    微信小程序对象赋值

    微信小程序对象赋值

    data{valueDa:{}}this.set...

    • 2354
    • 0
    小说正在扼杀我的阅读思考能力....

    小说正在扼杀我的阅读思考能力....

    从18岁就开始看第一本小说《诛仙》,慢慢的看到了现在28岁。...

    • 2343
    • 0

    猜你喜欢

    响应式博客新闻资讯

    响应式博客新闻资讯

    ...

    • 904
    • 0
    dede织梦接口发布后自动更新首页栏目页

    dede织梦接口发布后自动更新首页栏目页

    ...

    • 1323
    • 0
    严禁“嘚瑟”!!!

    严禁“嘚瑟”!!!

    自己只是收获一时快感但能让你产生“嘚瑟”“炫耀”的点已经就会...

    • 1627
    • 0
    css 固定宽高后图片裁剪

    css 固定宽高后图片裁剪

    object-fit: cover;...

    • 1204
    • 0
    获取分类信息

    获取分类信息

    当前分类的顶级分类信息...

    • 1492
    • 0

    标签

    • 标签2
    • 今天的天气
    • 织梦cms
    • pbootcms迁移
    • 企业微信
    • 微信小程序
    • zblog插件
    • pbootcms
    • thinkphp
    • 明天的天气
    嘿,欢迎咨询
    jstang博客
    回到顶部

    涉及到的所有程序逻辑仅用来学习交流,严禁用于非法用途,产生的一切后果自行承担! 。用户在使用程序时,应遵守相关法律法规,不得利用本软件进行任何违法活动 ,因用户违反本《协议》或使用程序造成的任何损失和法律责任,由用户自行承担,本程序不承担 任何责任。冀ICP备2022024290号-1