开发基本接⼝
1,接⼝配置填写服务器对接通知的接⼝地址及鉴权token
配置⽹页授权获取⽤户信息域名mytest(⽤于⽹站获取⽤户基本信息)
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("api.weixin.qq/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("api.weixin.qq/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 = "mp.weixin.qq/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("api.weixin.qq/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("api.weixin.qq/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN");
$result = json_decode($result);开发程序
var_dump($result);
}
//⽣成⾃定义菜单,客户端隔天刷新,可取消关注再关注实现⽴即刷新
public function genmenu(){
$cpage = "open.weixin.qq/connect/oauth2/authorize?appid=".$this->_wxappid."&redirect_uri=".urlencode("mytest/weixin/OpenIdPage")."&response_type=code&scope=snsapi_base&state=12345#wechat_redirect"
$ppage = "open.weixin.qq/connect/oauth2/authorize?appid=".$this->_wxappid."&redirect_uri=".urlencode("mytest/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("api.weixin.qq/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 "api.weixin.qq/cgi-bin/material/add_material?access_token=TVaBtXR8CJH3dd_dNaPae45a-aU2T1CpW2KsxUNjOlvpKWZ01QT-9BH1Jp_eumniu7ojpFUmRXn8oNgpQxNvgeYsv09QllK9gPvouV {"media_id":"im03apKihxUcy45i1Cu30E2WFdPONd_8yyG7VwE7as0","url":"https:\/\/mmbiz.qlogo\/mmbiz\/vyiaPGicTjvibZHtrldAfEahzD0RdQVS9iaXA90Y0uibu1kTOUSO7cu7CbsHlJicrHXubvnHrTmolibK8amJzQIPLAkGg\/0?wx_fmt=jpeg"查看
api.weixin.qq/cgi-bin/material/batchget_material?access_token=...
统计数量
api.weixin.qq/cgi-bin/material/get_materialcount?access_token=TVaBtXR8CJH3dd_dNaPae45a-aU2T1CpW2KsxUNjOlvpKWZ01QT-9BH1Jp_eumniu7ojpFUmRXn8oNgpQxNvgeYsv09QllK9gPvouVISUoo
{"voice_count":0,"video_count":0,"image_count":3,"news_count":0}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论