1. 微信企業號SDKphp
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×tamp=$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. 調用方法mysql
/* 提供獲取企業號應用、設置企業號應用、獲取應用列表的接口。 首頁 開始開發 ✔主動調用 ✔回調模式 認證接口 身份驗證 ✔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"]); } */