微信企业号SDK

1. 微信企业号SDK

  1 class class_wxqiye
  2 {
  3     var $corpid = CorpID;
  4     var $corpsecret = CorpSecret;
  5     var $agentid = AgentID;
  6 
  7     //构造函数,获取Access Token
  8     public function __construct($corpid = NULL, $corpsecret = NULL, $agentid = NULL)
  9     {
 10         if($corpid && $corpsecret){
 11             $this->corpid = $corpid;
 12             $this->corpsecret = $corpsecret;
 13             $this->agent = $agentid;
 14         }
 15 
 16         $con = mysql_connect(MYSQLHOST.':'.MYSQLPORT, MYSQLUSER, MYSQLPASSWORD);
 17         mysql_select_db(MYSQLDATABASE, $con);
 18         $result = mysql_query("SELECT * FROM `qyh_mngmgroup` WHERE `type` = 'access_token' AND `corpid` = '$this->corpid'");
 19         while($row = mysql_fetch_array($result))
 20         {
 21             $this->access_token = $row['value'];
 22             $this->expires_time = $row['expire'];
 23             break;
 24         }
 25         if (time() > ($this->expires_time + 3600)){
 26             $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpid."&corpsecret=".$this->corpsecret;
 27             $res = $this->http_request($url);
 28             $result = json_decode($res, true);
 29             $this->access_token = $result["access_token"];
 30             $this->expires_time = time();
 31             mysql_query("UPDATE `qyh_mngmgroup` SET `expire` = '$this->expires_time', `value` = '$this->access_token' WHERE `type` = 'access_token' AND `corpid` = '$this->corpid';");
 32         }
 33 
 34     }
 35 
 36     /*
 37     测试接口,获取微信服务器IP地址
 38     */
 39     // $result = $weixin->get_callback_ip();
 40     // var_dump(count($result['ip_list']));
 41     public function get_callback_ip()
 42     {
 43         $url = "https://qyapi.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$this->access_token;
 44         $res = $this->http_request($url);
 45         return json_decode($res, true);
 46     }
 47 
 48     /*
 49         1. 通讯录
 50     */
 51     //1.1 获取部门列表
 52     // $result = $weixin->get_department_list('2');
 53     public function get_department_list($id = 1)
 54     {
 55         $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$this->access_token."&id=".strval($id);
 56         $res = $this->http_request($url);
 57         return json_decode($res, true);
 58     }
 59 
 60        //1.2 创建部门
 61     public function create_department($data)
 62     {
 63         $url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=".$this->access_token;
 64         $res = $this->http_request($url, $this->array_to_json($data));
 65         return json_decode($res, true);
 66     }
 67 
 68        //1.3 更新部门
 69     public function update_department($data)
 70     {
 71         $url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=".$this->access_token;
 72         $res = $this->http_request($url, $this->array_to_json($data));
 73         return json_decode($res, true);
 74     }
 75 
 76     //1.4 删除部门
 77     public function delete_department($id)
 78     {
 79         $url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=".$this->access_token."&id=".strval($id);
 80         $res = $this->http_request($url);
 81         return json_decode($res, true);
 82     }
 83 
 84     //1.5 获取部门成员
 85     public function get_department_userlist($departmentid, $fetchchild = "1", $status = "0")
 86     {
 87         $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=".$this->access_token."&department_id=".strval($departmentid)."&fetch_child=".strval($fetchchild)."&status=".strval($status);
 88         $res = $this->http_request($url);
 89         return json_decode($res, true);
 90     }
 91 
 92     /*
 93     * 2. 素材文件
 94     */
 95     // 2.3 上传图片、语音、视频、文件等类型永久素材
 96     public function add_permanent_material($type, $file)
 97     {
 98         if (PHP_OS == "Linux"){        //Linux
 99             $data = array("media"  => "@".dirname(__FILE__).'/'.$file);
100         }else{                        //WINNT
101             $data = array("media"  => "@".dirname(__FILE__).'\\'.$file);
102         }
103         $url = "https://qyapi.weixin.qq.com/cgi-bin/material/add_material?agentid=".$this->agentid."&type=".$type."&access_token=".$this->access_token;
104         $res = $this->http_request($url, $data);
105         return json_decode($res, true);
106     }
107 
108     /*
109     * 3. 企业号应用
110     */
111     // 3.1 获取应用概况列表
112     public function get_agent_list()
113     {
114         $url = "https://qyapi.weixin.qq.com/cgi-bin/agent/list?access_token=".$this->access_token;
115         $res = $this->http_request($url, $data);
116         return json_decode($res, true);
117     }
118 
119     // 3.2 获取企业号应用
120     public function get_agent_info()
121     {
122         $url = "https://qyapi.weixin.qq.com/cgi-bin/agent/get?agentid=".$this->$agentid."&access_token=".$this->access_token;
123         $res = $this->http_request($url);
124         return json_decode($res, true);
125     }
126 
127     /*
128     * 4. 发送消息
129     */
130     public function send_message($type, $data, $touser = '@all', $safe = '1')
131     {
132         $msg = array();
133         $msg['touser']  = $touser;
134         $msg['agentid'] = $this->agentid;
135         $msg['msgtype'] = $type;
136         switch($type)
137         {
138             case 'text':
139                 $msg[$type]     = array('content'=>$data);
140                 break;
141             case 'news':
142                 $data2 = array();
143                 foreach ($data as &$item) {
144                     $item2 = array();
145                     foreach ($item as $k => $v) {
146                         $item2[strtolower($k)] = $v;
147                     }
148                     $data2[] = $item2;
149                 }
150                 $msg[$type] = array('articles'=>$data2);
151                 break;
152             case 'music':
153             case 'image':
154             case 'voice':
155             case 'video':
156             case 'file':
157                 $msg['media_id'] = $data;
158                 break;
159             default:
160                 $msg['text'] = array('content'=>"不支持的消息类型 ".$type);
161                 break;
162         }
163         $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$this->access_token;
164         return $this->http_request($url, $this->array_to_json($msg));
165     }
166 
167     /*
168     * 5. 自定义菜单
169     */
170     // 5.1 创建菜单
171     public function create_menu($button)
172     {
173         $data = $this->array_to_json(array('button' => $button));
174         $url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token."&agentid=".$this->agentid;
175         $res = $this->http_request($url, $data);
176         return json_decode($res, true);
177     }
178 
179     // 5.2 查询菜单
180     public function get_menu()
181     {
182         $url = "https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token."&agentid=".$this->agentid;
183         $res = $this->http_request($url);
184         return json_decode($res, true);
185     }
186 
187     /*
188     * 6. 身份验证
189     */
190     // 6.1 企业获取code
191     public function oauth2_authorize($redirect_url, $scope = "snsapi_base", $state = "")
192     {
193         $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->corpid."&redirect_uri=".urlencode($redirect_url)."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
194         return $url;
195     }
196 
197     // 6.2 根据code获取成员信息
198     public function oauth2_get_userinfo($code)
199     {
200         $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$this->access_token."&code=".$code;
201         $res = $this->http_request($url);
202         return json_decode($res, true);
203     }
204 
205     // 6.3 userid转换成openid接口
206     public function convert_openid($userid)
207     {
208         $data = $this->array_to_json(array('userid' => $userid, 'agentid'=>$this->agentid));
209         $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=".$this->access_token;
210         $res = $this->http_request($url, $data);
211         return json_decode($res, true);
212     }
213 
214     // 6.4 成员登录授权[企业内部开发者]
215     public function oauth2_login_page($redirect_url, $state = "", $usertype = "admin")
216     {
217         $url = "https://qy.weixin.qq.com/cgi-bin/loginpage?corp_id=".$this->corpid."&redirect_uri=".urlencode($redirect_url)."&state=".$state."&usertype=".$usertype;
218         return $url;
219     }
220 
221     // 6.5 获取企业号登录用户信息[成员登录授权]
222     public function oauth2_get_login_info($auth_code)
223     {
224         $data = $this->array_to_json(array('auth_code' => $auth_code));
225         $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token=".$this->access_token;
226         $res = $this->http_request($url, $data);
227         return json_decode($res, true);
228     }
229     
230     // 6.6 获取登录企业号官网的url[单点登录授权]
231     public function oauth2_get_login_url($login_ticket, $target = 'agent_setting')
232     {
233         $msg = array();
234         $msg['login_ticket'] = $login_ticket;
235         $msg['target'] = $target;
236         $msg['agentid'] = $this->agentid;
237         $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_login_url?access_token=".$this->access_token;
238         return $this->http_request($url, $this->array_to_json($msg));
239     }
240     
241     
242     //JS SDK 
243     /*
244     *  PART4 JS SDK 签名
245     *  PHP仅用于获得签名包,需要配合js一起使用
246     */
247     //生成长度16的随机字符串
248     public function createNonceStr($length = 16) {
249         $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
250         $str = "";
251         for ($i = 0; $i < $length; $i++) {
252             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
253         }
254         return $str;
255     }
256     
257     //获得JS API的ticket
258     private function getJsApiTicket() 
259     {
260         /*
261         //1. 数据库形式,与Access Token共用同一张表,mysql在创建微信类时初始化
262         $result = mysql_query("SELECT * FROM `qyh_token` WHERE `type` = 'jsapi_ticket'");
263         $result = mysql_query("SELECT * FROM `qyh_token` WHERE `type` = 'jsapi_ticket' AND `corpid` = '$this->corpid'");
264         while($row = mysql_fetch_array($result))
265         {
266             $this->jsapi_ticket = $row['value'];
267             $this->jsapi_expire = $row['expire'];
268             break;
269         }
270         if (time() > ($this->jsapi_expire + 3600)){
271             $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=".$this->access_token;
272             $res = $this->http_request($url);
273             $result = json_decode($res, true);
274             $this->jsapi_ticket = $result["ticket"];
275             $this->jsapi_expire = time();
276             mysql_query("UPDATE `qyh_mngmgroup` SET `expire` = '".$this->jsapi_expire."', `value` = '".$this->jsapi_ticket."' WHERE `type` = 'jsapi_ticket';");
277             mysql_query("UPDATE `qyh_mngmgroup` SET `expire` = '$this->jsapi_expire', `value` = '$this->access_token' WHERE `type` = 'access_token' AND `corpid` = '$this->corpid';");
278         }
279         return $this->jsapi_ticket;
280         */
281 
282         $result = mysql_query("SELECT * FROM `qyh_mngmgroup` WHERE `type` = 'jsapi_ticket'");
283         while($row = mysql_fetch_array($result))
284         {
285             $this->jsapi_ticket = $row['value'];
286             $this->jsapi_expire = $row['expire'];
287             break;
288         }
289         if ((!isset($this->jsapi_expire)) || (time() > ($this->jsapi_expire + 3600))){
290             $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=".$this->access_token;
291             $res = $this->http_request($url);
292             $result = json_decode($res, true);
293             var_dump($result);
294             $this->jsapi_ticket = $result["ticket"];
295             $this->jsapi_expire = time();
296             mysql_query("UPDATE `qyh_mngmgroup` SET `expire` = '$this->jsapi_expire', `value` = '$this->jsapi_ticket' WHERE `type` = 'jsapi_ticket';");
297         }
298 
299         return $this->jsapi_ticket;
300     }
301 
302     //获得签名包
303     public function getSignPackage() {
304         $jsapiTicket = $this->getJsApiTicket();
305         $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
306         $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
307         $timestamp = time();
308         $nonceStr = $this->createNonceStr();
309         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
310         $signature = sha1($string);
311         $signPackage = array(
312                             "appId"     => $this->corpid,
313                             "nonceStr"  => $nonceStr,
314                             "timestamp" => $timestamp,
315                             "url"       => $url,
316                             "signature" => $signature,
317                             "rawString" => $string
318                             );
319         return $signPackage;
320     }
321 
322     //多级数组转JSON(兼容中文、数字、英文、布尔型)(使用递归出现编码错误 !!! )
323     protected function array_to_json($array)
324     {
325         foreach ($array as $k => &$v) {
326             if (is_array($v)){
327                 foreach ($v as $k1 => &$v1) {
328                     if (is_array($v1)){
329                         foreach ($v1 as $k2 => &$v2) {
330                             if (is_array($v2)){
331                                 foreach ($v2 as $k3 => &$v3) {
332                                     if (is_array($v3)){
333                                         foreach ($v3 as $k4 => &$v4) {
334                                             $v3[$k4] = (is_string($v4))?urlencode($v4):$v4;
335                                         }
336                                     }else{
337                                         $v2[$k3] = (is_string($v3))?urlencode($v3):$v3;
338                                     }
339                                 }
340                             }else{
341                                 $v1[$k2] = (is_string($v2))?urlencode($v2):$v2;
342                             }
343                         }
344                     }else{
345                         $v[$k1] = (is_string($v1))?urlencode($v1):$v1;
346                     }
347                 }
348                 // $this->array_to_json($v);
349             }else{
350                 $array[$k] = (is_string($v))?urlencode($v):$v;
351             }
352         }
353         return urldecode(json_encode($array));
354     }
355 
356     //HTTP请求(支持HTTP/HTTPS,支持GET/POST)
357     protected function http_request($url, $data = null)
358     {
359         $curl = curl_init();
360         curl_setopt($curl, CURLOPT_URL, $url);
361         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
362         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
363         if (!empty($data)){
364             curl_setopt($curl, CURLOPT_POST, 1);
365             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
366         }
367         curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
368         $output = curl_exec($curl);
369         curl_close($curl);
370         return $output;
371     }
372 
373     //日志记录
374     private function logger($log_content)
375     {
376         if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
377             sae_set_display_errors(false);
378             sae_debug($log_content);
379             sae_set_display_errors(true);
380         }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
381             $max_size = 500000;
382             $log_filename = "log.xml";
383             if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
384             file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
385         }
386     }
387 }

 

2. 调用方法

/*
提供获取企业号应用、设置企业号应用、获取应用列表的接口。

首页
开始开发
    ✔主动调用
    ✔回调模式
认证接口
    身份验证
        ✔OAuth验证接口
        ✔userid与openid互换接口
    ✔成员登录授权
    ✔单点登录授权
资源接口
    管理企业号应用
        ✔获取企业号应用
        ✔设置企业号应用
        ✔获取应用概况列表
    自定义菜单
        ✔创建应用菜单
        ✔删除菜单
        ✔获取菜单列表
    管理通讯录
        成员关注企业号
        ✔管理部门
        ✔管理成员
        管理标签
        异步任务接口
    管理素材文件    ✔可上传
能力接口
    ✔发消息
    ✔接收消息与事件
    微信JS-SDK接口 未做,做一个试一下
    会话服务 没啥用
    客服服务 没哈用
    企业号微信支付 和服务号一样,只需要userid转openid,已有用例
    摇一摇周边 暂无权限
SaaS套件接口
    第三方应用授权
    通讯录权限体系
    管理后台单点登录
*/

/*
    //微信企业号API接口大全
    require_once('qiye.class.php');
    $weixin = new class_wxqiye();
*/


// $weixin = new class_wxqiye();


//1. 通讯录
//1.1 获取部门列表
// $result = $weixin->get_department_list('2');

//1.2 创建部门
// $data = array('name' => "战略部",
              // 'parentid' => "1",
              // 'order' => "1",
              // // 'id' => "10",
             // );
// $result = $weixin->create_department($data);

//1.5 获取部门成员
// $result = $weixin->get_department_userlist("7", "1", "0");

//2. 素材
//2.5 上传图片、语音、视频、文件素材
// $file = "fangbei.jpg";
// $result = $weixin->add_permanent_material("6", "image", $file);
// $file = "butterfly.mp4";
// $result = $weixin->add_permanent_material("6", "video", $file);
// $file = "cert.zip";
// $result = $weixin->add_permanent_material("6", "file", $file);

//3. 企业号应用
// $result = $weixin->get_agent_list();
// $result = $weixin->get_agent_info('6');

//4. 发送消息
// 发送文本消息
// $result = $weixin->send_message('text', "没有查到到订单记录");
// 发送图文消息
// $data[] = array("Title"=>"多图文1标题", "Description"=>"多图文1描述", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
// $data[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
// $data[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
// $result = $weixin->send_message("news", $data);

//5. 自定义菜单
// $button = array(array('name' => "点击跳转",
                      // 'sub_button' => array(
                                        // array('type' => "click",
                                              // 'name' => "点击推事件",
                                              // 'key'  => "COMPANY"
                                              // ),
                                        // array('type' => "view",
                                              // 'name' => "跳转URL",
                                              // 'url'  => "http://www.baidu.com/"
                                             // ),
                                    // )
                      // ),
                // array('name' => "扫码发图",
                      // 'sub_button' => array(
                                        // array('type' => "scancode_waitmsg",
                                              // 'name' => "扫码带提示",
                                              // 'key'  => "rselfmenu_2_1"
                                              // ),
                                        // array('type' => "scancode_push",
                                              // 'name' => "扫码推事件",
                                              // 'key'  => "rselfmenu_2_2"
                                              // ),
                                        // array('type' => "pic_sysphoto",
                                              // 'name' => "系统拍照发图",
                                              // 'key'  => "rselfmenu_2_3"
                                              // ),
                                        // array('type' => "pic_photo_or_album",
                                              // 'name' => "拍照或相册发图",
                                              // 'key'  => "rselfmenu_2_3"
                                              // ),
                                        // array('type' => "pic_weixin",
                                              // 'name' => "微信相册发图",
                                              // 'key'  => "rselfmenu_2_5"
                                              // )
                                    // )
                      // ),
                // array('type' => "location_select",
                      // 'name' => "发送位置",
                      // 'key'  => "rselfmenu_3_0",
                      // )
                // );
// $result = $weixin->create_menu($button);
// // $result = $weixin->get_menu();
// var_dump($result);


/*
//网页授权获得userid和openid
if (!isset($_GET["code"])){
    $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $jumpurl = $weixin->oauth2_authorize($redirect_url, "snsapi_base", "123");
    Header("Location: $jumpurl");
}else{
    $userinfo = $weixin->oauth2_get_userinfo($_GET["code"]);
    // array(2) { ["DeviceId"]=> string(32) "be434bab16db86bd40995edf1194ef3b" ["UserId"]=> string(6) "taojin" } 
    // array(2) { ["DeviceId"]=> string(32) "e0a66223f897a826717fc134930afe85" ["OpenId"]=> string(28) "o_UE0s2L8mVlEAhlScmE0dfjJojg" } 
    if (!isset($userinfo["OpenId"])){
        $openinfo = $weixin->convert_openid($userinfo["UserId"]);
        // array(4) { ["errcode"]=> int(0) ["errmsg"]=> string(2) "ok" ["openid"]=> string(28) "oxzslwktZytLTM7zwlU3QODJNzQ0" ["appid"]=> string(18) "wxcc23554f93463d7c" }
        $openid = $openinfo["openid"];
    }else{
        $openid = $userinfo["OpenId"];
    }
}

//获取企业号登录用户信息[成员登录授权]
if (!isset($_GET["auth_code"])){
    $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $jumpurl = $weixin->oauth2_login_page($redirect_url, "123", "member");
    Header("Location: $jumpurl");
}else{
    $userinfo = $weixin->oauth2_get_login_info($_GET["auth_code"]);
}

*/

 

posted @ 2019-07-15 15:13 方倍工作室 阅读(...) 评论(...) 编辑 收藏