微信公众号开发基本接口
1,接口配置填写服务器对接微信通知的接口地址及鉴权token
配置网页授权获取用户信息 域名mytest.com(用于网站获取用户基本信息)
2,服务器端实现
a,修改library/Curl.php扩展支持postjson格式数据
public function postjson($params = array(), $options = array()) { // If its an array (instead of a query string) then format it correctly if (is_array($params)) { $params = json_encode($params, JSON_UNESCAPED_UNICODE); } // Add in the specific options provided $this->options($options); $this->http_method('post'); $this->option(CURLOPT_POST, TRUE); $this->option(CURLOPT_POSTFIELDS, $params); $this->option(CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($params))); }
b,ci基本接口实现
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Weixin extends CI_Controller { var $_wxappid = "wxappid"; var $_wxappsecret = "wxappsecret"; var $_cachekey = "wx_access_token"; var $_cacheticket = "wx_ticket"; function __construct() { parent::__construct(); $this->load->model('weixin_model', 'weixin');//alias name } //获取AccessToken,有调用次数限制,存在Redis缓存 private function getAccessToken() { $token = $this->redis->get($this->_cachekey); if(is_null($token)){ $result = $this->curl->simple_get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_wxappid."&secret=".$this->_wxappsecret); $result = json_decode($result); if(array_key_exists("access_token", $result)){ $token = $result->access_token; $expire = $result->expires_in; } if(!is_null($token)){ $this->redis->setex($this->_cachekey, $expire - 1800, $token); } } return $token; } //获取Ticket用于生成QRCode private function getTicket($uid, $token) { $ticket = $this->redis->get($this->_cacheticket); if(is_null($ticket)){ $param = array( "expire_seconds"=>3600*4, "action_name"=>"QR_SCENE", "action_info"=>array( "scene" => array("scene_id"=>$uid), ), ); $result = $this->curl->simple_postjson("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token, $param); $result = json_decode($result); if(array_key_exists("ticket", $result)){ $ticket = $result->ticket; $expire = $result->expire_seconds; } if(!is_null($ticket)){ $this->redis->setex($this->_cacheticket, $expire - 1800, $ticket); } } return $ticket; } public function getQRCode() { $mac = $this->input->post("mac"); $extradata = 1234567; $token = $this->getAccessToken(); $ticket = $this->getTicket($extradata, $token); $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket); $data = array("code"=>0, "url"=>$url); echo $data; } //处理消息 private function handleMessage($postObj, $answer = "thank you for your message") { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $time = time(); //可返回图文消息,视频,音频,图片等(需要调用素材管理接口上传) $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $answer); return $resultStr; } //处理用户事件 private function handleEvent($postObj) { $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $event = $postObj->Event; //扫描二维码并关注 if($event == "subscribe"){ $eventkey = $postObj->EventKey; $extradata = str_replace("qrscene_","",$eventkey); $res = $this->weixin->subscribe($extradata, $fromUsername); if($res){ return $this->handleMessage($postObj, "subscribe success"); } } //取消关注公众号 else if($event == "unsubscribe"){ $res = $this->weixin->unsubscribe($fromUsername); if($res){ return $this->handleMessage($postObj, "unsubscribe success"); } } //已关注用户扫描 else if($event == "SCAN"){ $eventkey = $postObj->EventKey; $extradata = $eventkey; $res = $this->weixin->subscribe($extradata, $fromUsername); if($res){ return $this->handleMessage($postObj, "subscribe success"); } } return null; } //分发消息 private function dispatch() { $postStr = file_get_contents("php://input"); log_message("info", $postStr); if (!empty($postStr)){ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr); if($postObj->MsgType == "text"){ $keyword = trim($postObj->Content); if(is_null($keyword) or $keyword == ""){ return; } $resp = $this->handleMessage($postObj); }else{ $resp = $this->handleEvent($postObj); } } log_message("info", $resp); echo $resp; } //检查签名 private function check() { $signature = $this->input->get("signature"); $timestamp = $this->input->get("timestamp"); $nonce = $this->input->get("nonce"); $token = "weixin"; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; } return false; } public function process() { if(self::check()){ $echostr = $this->input->get("echostr"); if($echostr){ echo $echostr; } else{ self::dispatch(); } }else{ echo "error"; } } private function OpenIdPage() { $result = $this->curl->simple_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->_wxappid."&secret=".$this->_wxappsecret."&code=".$code."&grant_type=authorization_code"); $result = json_decode($result); return $rid; } public function UserInfoPage() { $result = $this->getUserToken(); $token = $result->access_token; $openid = $result->openid; $result = $this->curl->simple_get("https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN"); $result = json_decode($result); var_dump($result); } //生成自定义菜单,微信客户端隔天刷新,可取消关注再关注实现立即刷新 public function genmenu(){ $cpage = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->_wxappid."&redirect_uri=".urlencode("http://mytest.com/weixin/OpenIdPage")."&response_type=code&scope=snsapi_base&state=12345#wechat_redirect"; $ppage = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->_wxappid."&redirect_uri=".urlencode("http://mytest.com/weixin/UserInfoPage")."&response_type=code&scope=snsapi_userinfo&state=12345#wechat_redirect"; $token = $this->getAccessToken(); $param = array( "button" => array( array("type"=>"view","name"=>"不需要授权的页面","url"=>$cpage), array("type"=>"view","name"=>"需要授权的页面","url"=>$cpage) ) ); $result = $this->curl->simple_postjson("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token, $param); var_dump($result); } } /* End of file weixin.php */ /* Location: ./application/controllers/weixin.php */
c,素材管理等接口
上传 curl -F media=@1.jpg -F type=image -v "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=TVaBtXR8CJH3dd_dNaPae45a-aU2T1CpW2KsxUNjOlvpKWZ01QT-9BH1Jp_eumniu7ojpFUmRXn8oNgpQxNvgeYsv09QllK9gPvouVISUoo" {"media_id":"im03apKihxUcy45i1Cu30E2WFdPONd_8yyG7VwE7as0","url":"https:\/\/mmbiz.qlogo.cn\/mmbiz\/vyiaPGicTjvibZHtrldAfEahzD0RdQVS9iaXA90Y0uibu1kTOUSO7cu7CbsHlJicrHXubvnHrTmolibK8amJzQIPLAkGg\/0?wx_fmt=jpeg"}⏎ 查看 https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=... 统计数量 https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=TVaBtXR8CJH3dd_dNaPae45a-aU2T1CpW2KsxUNjOlvpKWZ01QT-9BH1Jp_eumniu7ojpFUmRXn8oNgpQxNvgeYsv09QllK9gPvouVISUoo {"voice_count":0,"video_count":0,"image_count":3,"news_count":0}