微信用户扫描不同渠道二维码关注服务号,回复不同欢迎语,并自动分组。
前不久公司需要做一个微信用户扫描不同渠道二维码关注服务号,回复不同的欢迎语,计算扫描已关注数,扫描未关注数,并自动分组的功能。
今天刚做好这些功能,分享一下。 这是基于ecshop进行开发的。
数据库表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `weixin_qr_channel`
-- ----------------------------
DROP TABLE IF EXISTS `weixin_qr_channel`;
CREATE TABLE `weixin_qr_channel` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`channel_name` varchar(120) NOT NULL,
`qr_url` varchar(500) DEFAULT NULL,
`attention_num` int(11) unsigned NOT NULL DEFAULT '0',
`datetime` datetime DEFAULT NULL,
`ticket` varchar(100) DEFAULT NULL,
`content` varchar(500) DEFAULT NULL,
`group_id` int(8) DEFAULT NULL,
`scan_num` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
后台代码
<?php
/**
* 功能:二维码关注 自动分组
* 屌丝程序员
*/
define ( 'IN_ECS', true );
require (dirname ( __FILE__ ) . '/includes/init.php');
include_once (ROOT_PATH . '/includes/cls_image.php');
$_REQUEST ['act'] = trim ( $_REQUEST ['act'] );
if ($_REQUEST ['act'] == 'list') {
$channel_list = get_qr_channel_list();
$smarty->assign ( 'channel_list', $channel_list );
$smarty->display ( 'weixin_qr_channel_list.html' );
} elseif ($_REQUEST ['act'] == 'add') {
if ($_POST) {
$date ['channel_name'] = $_POST ['channel_name'];
$date ['group_id'] = $_POST ['group_id'];
$date ['content'] = $_POST ['content'];
$date ['datetime'] = date ( "Y-m-d H:i:s", time () );
if($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('weixin_qr_channel'), $date))
{
$id = $GLOBALS['db']->insert_id();
$qr_img =get_qr_img($id);
$date2 ['qr_url'] = $qr_img['url'];
$date2 ['ticket'] = $qr_img['ticket'];
$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('weixin_qr_channel'), $date2,'update'," `id` = '$id' " );
$link [] = array (
'href' => 'weixin_qr_channel.php?act=list',
'text' => '关键自动回复'
);
sys_msg ( '添加成功', 0, $link );
}else
{
sys_msg ( '添加失败');
}
} else {
require (ROOT_PATH . 'includes/fckeditor/fckeditor.php');
$editor = new FCKeditor ( 'contents' );
$editor->BasePath = '../includes/fckeditor/';
$editor->ToolbarSet = 'Normal';
$editor->Width = '60%';
$editor->Height = '320';
$editor->Value = $content ['template_content'];
$FCKeditor = $editor->CreateHtml ();
$smarty->assign ( 'FCKeditor', $FCKeditor );
$smarty->assign ( 'action_link', $action_link );
//分组
$group_list = get_group_list();
$smarty->assign ( 'group_list', $group_list );
$smarty->assign ( 'formAction', 'add' );
$smarty->display ( 'weixin_qr_channel.html' );
}
}
elseif($_REQUEST['act'] == 'edit') {
if($_POST){
$id = trim($_POST['id']);
$date ['channel_name'] = $_POST ['channel_name'];
$date ['group_id'] = $_POST ['group_id'];
$date ['content'] = $_POST ['content'];
$date ['datetime'] = date ( "Y-m-d H:i:s", time () );
$qr_img =get_qr_img($id);
$date ['qr_url'] = $qr_img['url'];
$date ['ticket'] = $qr_img['ticket'];
if($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('weixin_qr_channel'), $date,'update'," `id` = '$id' " ))
{
$link [] = array (
'href' => 'weixin_qr_channel.php?act=list',
'text' => '关键词自动回复'
);
sys_msg('修改成功',0,$link);
}else
{
sys_msg ( '修改失败');
}
}else
{
$id = $_GET['id'];
$channel = $db->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('weixin_qr_channel')." WHERE `id` = $id");
$smarty->assign ( 'channel', $channel );
//分组
$group_list = get_group_list();
$smarty->assign ( 'group_list', $group_list );
$smarty->assign ('formAction', 'edit' );
$smarty->display('weixin_qr_channel.html');
}
}
elseif($_REQUEST['act'] == 'remove') {
$id = $_GET ['id'];
$sql = "DELETE FROM " . $GLOBALS ['db']->table ( 'weixin_qr_channel' ) . " WHERE `id` = $id";
if ($GLOBALS ['db']->query ( $sql )) {
$link [] = array (
'href' => 'weixin_qr_channel.php?act=list',
'text' => '二维码关注渠道管理'
);
sys_msg ( '删除成功', 0, $link );
} else {
sys_msg ( '删除失败' );
}
}
function get_group_list()
{
//第一步:获取access_token
$appid = ''; // 是 应用唯一标识
$appSecret = '';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
$result = https_request($url);
$result = json_decode($result, true);
$access_token = empty($result['access_token']) ? '' : $result['access_token'];
if(!empty($access_token))
{
//第二步:查询所有分组
$url2 = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$access_token";
$result2 = https_request($url2);
$result2 = json_decode($result2, true);
return $result2['groups'];
}
function https_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
function get_qr_img($scene_id)
{
//第一步:获取access_token
$appid = ''; // 是 应用唯一标识
$appSecret = '';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
$result = https_request($url);
$result = json_decode($result, true);
$access_token = empty($result['access_token']) ? '' : $result['access_token'];
if(!empty($access_token))
{
//第二步:创建二维码ticket接口 /qrcode/create
$url2 = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
//渠道值 scene_id
$strJson = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
$result2 = https_request($url2,$strJson);
$result2 = json_decode($result2, true);
$ticket = empty($result2['ticket']) ? '' : $result2['ticket'];
//第三步获取二维码
if (!empty($ticket)) {
$url3 = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=$ticket";
return array('url'=>$url3,'ticket'=>$ticket);
}
}
return array('url'=>'','ticket'=>'');
}
function https_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
function get_qr_channel_list() {
$sql = "SELECT * FROM ".$GLOBALS['ecs']->table('weixin_qr_channel') ;
$res = $GLOBALS['db']->getAll($sql);
return $res;
}
?>
微信接口代码
if ($postObj->MsgType == 'event') {
$Eventkeyword = $postObj->EventKey;
$Event = empty($postObj->Event) ? '' : $postObj->Event ;
$EventKey = empty($postObj->EventKey) ? '' : $postObj->EventKey ;
if ($Eventkeyword ==''){
$msgType = "text";
$lang['regmsg'] = $db -> getOne("SELECT `lang_value` FROM ".$weixinlangtable." WHERE `lang_name` = 'regmsg'");
$contentStr = $lang['regmsg'];
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
$contentStr = '绑定麦美美帐号可享更多服务'."\r\n".'<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8892dd7d58eec829&redirect_uri=http%3A%2F%2Fm.wm18.com%2Fuser.php%3Fact%3Dwx_login_action&response_type=0ab7f72a0390a00e660a6c443e2ea798&scope=snsapi_userinfo&state=320#wechat_redirect">点击这里,立即绑定</a>';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
exit;
}
else if ($Event == 'subscribe') {
//关注 自动分组
if(!empty($EventKey))
{
//关注加累计数
$id = str_replace('qrscene_','',$EventKey);
$sql = "UPDATE ".$GLOBALS['ecs']->table('weixin_qr_channel')." SET `attention_num`=`attention_num`+1 WHERE id = '$id'";
$db -> query($sql);
//获取分组id
$sql = "SELECT `group_id` FROM ".$GLOBALS['ecs']->table('weixin_qr_channel')." WHERE id = '$id' ";
$group_id = $GLOBALS['db']->getOne($sql);
logResult($group_id .' 分组一 '.$postObj->FromUserName);
//不为空的话 进行分组
if(!empty($group_id))
{
logResult($group_id .' 分组 '.$postObj->FromUserName);
$openid = $postObj->FromUserName ;
if(!empty($openid))
{
change_group($openid,$group_id);
logResult('分组操作调用函数');
}
}
//关注后回复欢迎语
$sql = "SELECT `content` FROM ".$GLOBALS['ecs']->table('weixin_qr_channel')." WHERE id = '$id' ";
$contentStr = $GLOBALS['db']->getOne($sql);
$msgType = "text";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
$contentStr = '绑定麦美美帐号可享更多服务'."\r\n".'<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8892dd7d58eec829&redirect_uri=http%3A%2F%2Fm.wm18.com%2Fuser.php%3Fact%3Dwx_login_action&response_type=0ab7f72a0390a00e660a6c443e2ea798&scope=snsapi_userinfo&state=320#wechat_redirect">点击这里,立即绑定</a>';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}
else if ($Event == 'SCAN') {
//扫描
$id = $EventKey;
$sql = "UPDATE ".$GLOBALS['ecs']->table('weixin_qr_channel')." SET `scan_num`=`scan_num`+1 WHERE id = '$id'";
$db -> query($sql);
}
else if ($Event == 'unsubscribe') {
//取消关注
}
else{
$keyword = $postObj->EventKey;
}
}
微信接口用到的函数
writeLog();
function writeLog()
{
// logResult('REQUEST: '.json_encode($_REQUEST));
logResult('GET: '.json_encode($_GET));
logResult('POST: '.json_encode($_POST));
$xml = file_get_contents('php://input');
logResult('XML: '.$xml);
}
function logResult($word='') {
$url = $_SERVER['PHP_SELF'];
$filename = substr( $url , strrpos($url , '/')+1 );
$filename = substr($filename,0,-4).'.txt';
$fp = fopen($filename ,"a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".date("Y-m-d H:i:s",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
}
function change_group($openid,$group_id)
{
logResult('进入分组函数');
//第一步:获取access_token
$appid = ''; // 是 应用唯一标识
$appSecret = '';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
$result = https_request($url);
$result = json_decode($result, true);
$access_token = empty($result['access_token']) ? '' : $result['access_token'];
logResult('分组操作1'.$access_token);
if(!empty($access_token))
{
//第二步:创建二维码ticket接口 /qrcode/create
$url2 = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=$access_token";
//渠道值 scene_id
$strJson = '{"openid":"'.$openid.'","to_groupid":'.$group_id.'}';
// $data['openid'] = $openid;
// $data['to_groupid'] = $group_id;
// $strJson = json_encode($data);
logResult('分组操作2:'.$strJson);
$result2 = https_request($url2,$strJson);
logResult('分组操作3:'.$result2);
}else
{
logResult('没有获取到access_token');
}
}
function https_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}