Introduction to WeChat development user groups

高洛峰
Release: 2017-03-22 16:26:05
Original
1780 people have browsed it

1: Create a user group

Like QQ, WeChat can create group names, delete group names, modify group names, and query group names. These operations are a series of interfaces. You only need to call the relevant interfaces. , and send it in the form of curl, you can get relevant results

Create groups

A public account supports the creation of up to 100 groups.

Interface call request description

http request method: POST (please use https protocol) https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN

POST data format: json

POST data example: {"group":{"name":"test"}}

Parameter description

Parameter Description

access_token Calling interface credential

name Group name (within 30 characters)

Return description Example of returned JSON data packet when normal:

{

"group": {

"id": 107,

"name": "test"

}

}

The following is the implementation of the relevant code

We need to send the data packet through curl. The returned result is json data in the form of StdClass. We need to convert stdClass into an array. form, so we create a func.php file, and the related operations of the subsequent groups are based on these functions

<?php 
       //设定appID 和secret
	   define ("APPID","wx70fe852945a945b6",true);
	   define ("SECRET",&#39;d05c2fc161d71c8317331a39044a7d93&#39;,true);
	   $APPID="wx70fe852945a945b6";
	   $SECRET="d05c2fc161d71c8317331a39044a7d93";
      function curl($url,$data=null)
	  {
		   //初始化
		   $curl=curl_init();
		   curl_setopt($curl, CURLOPT_URL, $url);//设置传输链接
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);//设置SSL凭证
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false );
           curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//是否显示在浏览器上
		   if(!empty($data))
		   {
			   //进行post数据
			   curl_setopt($curl,CURLOPT_POST,1);
			   curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
			   }
			$result=curl_exec($curl);//执行curl
			curl_close($curl);//关闭curl
			return $result;
		  }
		   function transition ($data)
	  {
		    if(is_object($data))
			{
				  $data=(array)$data;
				}
			if(is_array($data))
			{
				 foreach($data as $key=>$value)
				 {
					   $data[$key]=transition($value);
					 }
				}
				return $data;
		  }
		  //将多维数组转成字符串
		   function recount($result)
		{
			    if(is_array($result))
				{
			   foreach($result as $key=>$value)
			   {    
				  recount($value); 
				  return $value;
				   }
				  
				}
				
				
			}
		  //access_token链接地址
		  $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$SECRET";
		 //获取access_token.将返回的json格式转成数组,返回一个数组形式的access_token
		 $access_token=(array)json_decode(curl($access_token_url));
		 $access_token=$access_token['access_token'];
		
?>
Copy after login

Using the above access_token we can do whatever we want

First We create the group, and we name the file creategroup.php

1 Interface display

looks like very simple HTML code, I believe anyone with HTML basics can write it

So how to create a group? It's very simple. We just need to submit the API link to create the group.

Related code

  <?php  echo &#39;<meta http-equiv="content-type" content="text/html; charset=utf-8">'; 
?>
<!doctype html>
<html>
<head>
<title>无标题文档</title>
</head>
<body>
      <form action="#" method="post">
         <p>新建分组</p>
         <input type="text" name="tag" placeholder="新建一个分组">
         <input type="submit" name="-1" id="sub" value="提交">
         
      </form>
      <?php 
	     //如果提交成功,那么进行组的创建
	         if(isset($_POST[-1]))
			  {
	          
			     function create_group()
				{    require "func.php";
					 $create_url="https://api.weixin.qq.com/cgi-bin/tags/create?access_token=$access_token";
			         $tag=$_POST[&#39;tag&#39;];//获取组名
					$poststr="
					          {
								  \"tag\":
								      {
										  \"name\":\"$tag\";
									  }
								  }
					";		
					if($result=curl($create_url,$poststr))
	{
		 echo "<script type=\"text/javascript\">alert('执行成功,三秒之后将自动跳回主页')</script>";
		 //设置跳转回主页
		  echo "<script type=\"text/javascript\">setTimeout(window.navigate(\"getgroup.php\"),3000)</script>";
		}
	else
	{echo "<script type=\"text/javascript\">alert('执行失败')</script>";}
	
					}
					create_group();
			  }
			  
	  ?>
</body>
</html>
Copy after login

2: The next step is to display all the group names. Let's take a look at the WeChat official website first. Document

Query all groups

Interface call request description

http request method: GET (please use https protocol) https://api.weixin.qq.com/ cgi-bin/groups/get?access_token=ACCESS_TOKEN

Parameter description

Parameter description

access_token Call interface credential

Return description Return JSON when normal Data packet example:

{
    "groups": [
        {
            "id": 0, 
            "name": "未分组", 
            "count": 72596
        }, 
        {
            "id": 1, 
            "name": "黑名单", 
            "count": 36
        }, 
        {
            "id": 2, 
            "name": "星标组", 
            "count": 8
        }, 
        {
            "id": 104, 
            "name": "华东媒", 
            "count": 4
        }, 
        {
            "id": 106, 
            "name": "★不测试组★", 
            "count": 1
        }
    ]
}
Copy after login

Parameter description

Parameter description

groups Public platform group information list

id Group id, assigned by WeChat

name Group name, UTF8 encoding

count Number of users in the group

JSON data packet example when there is an error (this example is an invalid AppID error):

Official document for The returned json data is very clear. A group name contains basic information, group id, group name and the number of users in the group. We cannot directly display the returned json data on the page, so how do we parse json? What WeChat returns to us is a json of stdclass type, so in the first step we need to convert json into an array. There is a json_decode() function in php. This function can convert json data into an array of stdclass. stdclass is not equal to an array. , so we also need to talk about converting stdclass into array form. The transition() function in func.php has such a function.

Let’s first take a look at the page display and see what the data we get from Tencent through curl looks like.

In the above picture, we created a table. The first line is a create new The function of the group, in the following lines, we can see the group number, group name, and the number of people in the group. So how is this done? It's very simple. After we have obtained the returned json data, we wrap the json data and make the json into an array form. So how to implement data packaging? It's also very simple. We keep calling the parsing function, finally convert it into an array, and then traverse the array.

Show source code: getGroup.php

 <body>
     <div id="box">
    <div id="group">
<?php 
      require "func.php";
  $groupurl="https://api.weixin.qq.com/cgi-bin/groups/get?access_token={$access_token}";
  $result=json_decode(curl($groupurl));//获取包装之后的数据,以数组的形式存储
  //$result=curl($groupurl);
   //将STDclass类型转为数组类型
  function G_transition ($data)
  {
    if(is_object($data))
{
  $data=(array)$data;
}
if(is_array($data))
{
 foreach($data as $key=>$value)
 {
   $data[$key]=G_transition($value);
 }
}
return $data;
  }
  $result=G_transition($result);  
  function G_recount($result)
{
    if(is_array($result))
{
   foreach($result as $key=>$value)
   {    
  G_recount($value); 
  return $value;
   }
}
}
$resultG=G_recount($result);
echo "<table border=\"1px dashed\" bordercolor=\"#FF3333\">";
     echo "<tr><th colspan=\"3\"><a href=\"createGroup.php\">创建一个新组</a></th></tr>";
 echo "<th>编号</th><th>组名</th><th>人数</th>";
for($i=0;$i<count($resultG);$i++)
{
  echo "<tr>";
 foreach ($resultG[$i] as $key=>$value)
   { 
  if($key==&#39;id&#39;)
  {
  echo "<td  align=\"center\"title=\"\">[$value]<a href=\"delete.php?num=$value\">删除</a><a href=\"modify.php?num=$value\">修改</a></td>";
  }
  else 
  {
        echo "<td> $value</td>";
  }
}
echo "</tr>";
}
echo "</table>";
?>
      </div>
      <hr/> 
       <div>
          <hr/>
Copy after login

3: How do we modify the group name

修改分组名

接口调用请求说明

http请求方式: POST(请使用https协议)https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN

POST数据格式:json

POST数据例子:{"group":{"id":108,"name":"test2_modify2"}}

参数说明

参数 说明

access_token 调用接口凭证

id 分组id,由微信分配

name 分组名字(30个字符以内)

返回说明 正常时的返回JSON数据包示例:

{"errcode": 0, "errmsg": "ok"}

错误时的JSON数据包示例(该示例为AppID无效错误):

官方文档提供了修改分组名的接口,所以我们可以做一个修改的链接和一个修改组的modify.php文件

根据官方文档,我们需要通过组id才能进行修改,根据我们在创建组的时候传输过来的json数据中我们可以获取到组id,所有我们可以通过创建链接的方式,当点击链接的时候,会把组id以get的方式传送到modify文件中,而modify.php可以通过$_GET的形式接收组id.

我们先写好这个传送组id的链接,

      for($i=0;$i<count($resultG);$i++)
{
  echo "<tr>";
 foreach ($resultG[$i] as $key=>$value)
   { 
  if($key==&#39;id&#39;)
  {
  echo "<td  align=\"center\"title=\"\">[$value]<a href=\"delete.php?num=$value\">删除</a><a href=\"modify.php?num=$value\">修改</a></td>";
  }
  else 
  {
        echo "<td> $value</td>";
  }
}
echo "</tr>";
}
Copy after login

代码中,我们对返回的数组进行遍历,如果发现key值是id,那么我们将值获取过来并且加入到链接尾部,注意get方式的写法

echo "[$value]删除修改";

跳转到modify.php页面后,我们进行相关的处理,在该页面上,我们仍然有一个HTML输入框

代码如下:

    <form action="#" method="post">
      <p>更新组名</p>
      <input type="hidden" name="num" value="<?php echo $_GET[&#39;num&#39;]?>">
      <input  type="text"id="modify" name="name">
      <input type="submit" value="修改" name="-1">
  </form>
<?php 
    //此程序用于修改标签组
function modify()
{     $num=$_POST[&#39;num&#39;];
      $name=$_POST[&#39;name&#39;];
  require "func.php";
  $modify_url="https://api.weixin.qq.com/cgi-bin/tags/update?access_token=$access_token";
  //post过去的数据
  $poststr="
         {
   \"tag\":
         {
  \"id\":\"$num\",
  \"name\":\"$name\"
 }
 }
  ";
  $result=(array)json_decode(curl($modify_url,$poststr));
  $result=$result[&#39;errmsg&#39;];
  if($result==&#39;ok&#39;)
  {
     echo "<script type=\"text/javascript\">
         alert(\"$result\");
      </script>";
//进行页面跳转
 echo "<script type=\"text/javascript\">
             setTimeout(window.location.href=\"getgroup.php\",3000);
    </script>";
  }
else
{
 echo "<script type=\"text/javascript\">
         alert(&#39;wrong&#39;);
      </script>";
}
}
if(isset($_POST[&#39;-1&#39;]))
{
modify();
}
?>
Copy after login

如果执行成功,那么会进行弹出提醒框,等待五秒后自动跳转回getGroup.php页面

4:删除组

组名一般不允许删除,但是微信平台仍然给出了相关的删除接口

注意本接口是删除一个用户分组,删除分组后,所有该分组内的用户自动进入默认分组。 接口调用请求说明

http请求方式: POST(请使用https协议)https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=ACCESS_TOKEN

POST数据格式:json

POST数据例子:{"group":{"id":108}}

参数说明

参数 说明

access_token 调用接口凭证

group 分组

id 分组的id

返回说明 正常时的返回JSON数据包示例:

通过传递的json数据,我们只需要将组id进行传递到delete.php页面并进行相关的删除操作即可

代码显示:

    <?php 
    //该段程序用来删除组标签,成功之后会给予提示,并且跳转回getgroup.php页面
function delete()
{
$num=$_GET[&#39;num&#39;];//接收来自getgroup页面的编号
require "func.php";
$delete_url="https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=$access_token";
$data=json_encode(array("tag"=>array("id"=>$num)));
//如果curl函数执行成功,那么会返回一个状态值
if($result=curl($delete_url,$data))
{
 echo "<script type=\"text/javascript\">alert(&#39;执行成功,三秒之后将自动跳回主页&#39;)</script>";
 //设置跳转回主页
  echo "<script type=\"text/javascript\">setTimeout(window.history.back(-1),8000)</script>";
}
else
{echo "<script type=\"text/javascript\">alert(&#39;执行失败&#39;)</script>";}
}
delete();
?>
Copy after login

5:对组成员进行批量移动

有时候我们需要对组内的成员进行移动到其他的组里面,在这点上,微信平台也给出了相应的接口我们先看官方的文档说明

批量移动用户分组

接口调用请求说明

http请求方式: POST(请使用https协议)https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN

POST数据格式:json

POST数据例子:{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}

参数说明

参数 说明

access_token 调用接口凭证

openid_list 用户唯一标识符openid的列表(size不能超过50)

to_groupid 分组id

返回说明 正常时的返回JSON数据包示例:

{"errcode": 0, "errmsg": "ok"}

从传递的json数据可以看到,具有一个open_list和一个to_groupid,分别表示要移动的组成员的openid和将要移动的组id.那么我们如何开始移动呢?现在已基本清楚了,只需要把openid传递到open_list,将组id传递到to_groupid中,然后将包装好的json数据通过curl函数post过去.在批量分组之前,我们还要知道一件事,如何获取用户的相关信息,这个信息指的是用户微信上设置的性别,省份,国家,语言,所属组等等的相关信息,同样,微信提供了获取用户信息的接口,参照上述解决方法就可以获取到用户的相关的信息

以下是获取到的用户表

通过第一列的选择之后,在选择要分的组,点击移动就可以将用户移动到想要的组里面,下图是移动后的展示

所属组编号发生了变化

源代码展示

<form action="move.php" method="post">
          <table border="1px">
               <th>选择移动</th>
               <th>昵称</th>
               <th>性别</th>
               <th>语言</th>
               <th>所在城市</th>
               <th>省份</th>
               <th>国家</th>
               <th>头像</th>
               <th>加入时间</th>
               <th>备注名</th>
               <th>所属组</th>
               <th rowspan="10">
                     <?php 
    echo " <select name=\"group\">";
 $count=count($resultG);
 foreach($resultG as $key)//遍历包装好的json数据,已经转成了多维数组
 {
 echo "<option value=\"$key[id]\" >$key[name] </option>";                  $count--;  //获取组ID
 }
echo "</select>"; 
echo "<input type=\"submit\" name=\"-1\" value=\"移动\">";
?>
               </th>
              <?php 
       foreach($list[&#39;data&#39;] as $key)
   {
      //$list[&#39;data&#39;]是已经包装好的json数据,将原来的stdclass转为了多维数组
     // $result=count($key);
      //var_dump($result);
    foreach($key as $value)
{
 echo "<tr>";
   $info_url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$value&lang=zh_CN";
   $info=transition(json_decode(curl($info_url)));                              //var_dump($info);
   //echo "<hr>";
  //  global $userinfo;
//$userinfo=$info;
//var_dump($userinfo);
   foreach($info as $key=>$value)
   {
   //对表格进行相关的修饰,进行相关的判断
    switch($key)
{ 
  //如果是id,那么做成一个复选框
 case "openid":
     echo "<td align=\"center\">
 <input type=\"checkbox\" value=\"$value\"name=\"openid[]\"/>
      </td>";
     case "subscribe"://忽略相关的描述,不对这个字段生成列
 break;
 //如果是性别,性别值1代表男,0代表女,2代表并未填写
 case "sex":
      if($value==1)
  {
 echo "<td>男</td>"; }
  else if($value==0)
  {
 echo "<td>女</td>";  }
 else
   {
   echo "<td>暂未填写</td>"; }
  break;
 //如果是头像链接,那么生成一个50*50像素的图片
 case "headimgurl";
 echo "<td>
      <img src=\"$value\" height=\"50px\" width=\"\50px\">
       </td>";
 break;
 //以下是默认列
 case "nickname":
 case "language":
 case "city":
 case "province":
 case "country":
 case "subscribe_time":
 echo "<td>$value</td>";
 break;
 //如果remark的值为空,那么备注名是空值
 case "remark":
  if(empty($value))
  {
   echo "<td>暂无</td>";
  }
else
{
echo "<td>$value</td>";
}
break;
case "groupid":
      echo"<td>$value</td>";
  break;
}
   }
 echo "</tr>";
}
   }
  ?>
          </table>
        </form>
       </div>
       <hr / color=\"#9900CCd\">
   </div>
</body>
move.php的代码 
  <?php  
    //此程序用于移动分组
  $member=array();
 $member=$_POST[&#39;openid&#39;];//获取选中的openid
 $groupid=$_POST[&#39;group&#39;];//获取组id
require "func.php";
$move_url="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=$access_token";
    for($i=0;$i<count($member);$i++)
{
  $poststr="{\"openid\":\"$member[$i]\",\"to_groupid\":$groupid}";
   $result=curl($move_url,$poststr);
}
$result=(array)json_decode($result);
if($result[&#39;errmsg&#39;]==&#39;ok&#39;)
{
 echo "
   <script type=\"text/javascript\">window.alert(&#39;移动成功&#39;)</script>
   <script type=\"text/javascript\">
    setTimeout(\"window.location.href=&#39;getgroup.php&#39;\",5000);
   </script>
 ";
}
?>
Copy after login


The above is the detailed content of Introduction to WeChat development user groups. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!