#CI框架控制器
<?php
if ( !
defined('BASEPATH'))
exit('No direct script access allowed'
);
/***
CI框架整合微信
2014.9.15
作者:黄国金
**/
define('TOKEN', 'hgj123'
);
class Weixin
extends CI_Controller
{
#构造函数
function __construct()
{
#调用父类的构造函数
parent::
__construct();
#以get的形式获取参数
parse_str(
$_SERVER['QUERY_STRING'],
$_GET);
}
#在微信平台上设置的对外 URL
public function message()
{
#判断是否接入微信的验证
if (
$this->
_valid())
{
#判判断是不是验证过
$echostr =
$this->input->get('echostr'
);
if (!
empty(
$echostr))
{ #未验证
$this->load->view('valid_view',
array('output' =>
$echostr));
}
else
{
# 处理用户消息
$this->
_responseMsg();
}
}
else#验证失败
{
$this->load->view('valid_view',
array('output' => 'Error!'
));
}
}
#用于接入微信的验证
private function _valid()
{ #获取token
$token =
TOKEN;
$signature =
$this->input->get('signature'
);
$timestamp =
$this->input->get('timestamp'
);
$nonce =
$this->input->get('nonce'
);
$tmp_arr =
array(
$token,
$timestamp,
$nonce);
sort(
$tmp_arr);
$tmp_str =
implode(
$tmp_arr);
$tmp_str =
sha1(
$tmp_str);
return (
$tmp_str ==
$signature);
}
#处理用户发送过来的消息
private function _responseMsg()
{
#获取获取表单提交过来的数据
$post_str =
file_get_contents('php://input'
);
#判断是否为空
if (!
empty(
$post_str))
{
#解析微信传过来的 XML 内容
$post_obj =
simplexml_load_string(
$post_str, 'SimpleXMLElement',
LIBXML_NOCDATA);
$from_username =
$post_obj->
FromUserName;
$to_username =
$post_obj->
ToUserName;
#接受用户输入的内容
$keyword =
trim(
$post_obj->
Content);
#如果内容不为空
if (!
empty(
$keyword))
{
#文本类型的消息,本示例只支持文本类型的消息
$type = "text"
;
$content =
$this->_parseMessage(
$keyword);
#数据数组
$data =
array(
'to' =>
$from_username,
'from' =>
$to_username,
'type' =>
$type,
'content' =>
$content,
);
#分配数据
$this->load->view('response_view',
$data);
}
else
{#如果为空
$type = "text"
;
$content = "请输入文字"
;
#数据数组
$data =
array(
'to' =>
$from_username,
'from' =>
$to_username,
'type' =>
$type,
'content' =>
$content,
);
#分配数据
$this->load->view('response_view',
$data);
}
}
else
{ #错误
$this->load->view('valid_view',
array('output' => 'Error!'
));
}
}
#解析用户输入的字符串
private function _parseMessage(
$keyword)
{
#开启错误日记
log_message('debug',
$keyword);
#处理用户的关键字
return '你好~!~'
;
}
}
#输出界面 view试图
<xml>
<ToUserName><![CDATA[<?=
$to?>]]></ToUserName>
<FromUserName><![CDATA[<?=
$from?>]]></FromUserName>
<CreateTime><?=
time()?></CreateTime>
<MsgType><![CDATA[<?=
$type?>]]></MsgType>
<Content><![CDATA[<?=
$content?>]]></Content>
<FuncFlag>0</FuncFlag>
</xml>
转载于:https://www.cnblogs.com/hgj123/p/3972838.html