微信开发接口

1.开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:

1)将token、timestamp、nonce三个参数进行字典序排序

2)将三个参数字符串拼接成一个字符串进行sha1加密

3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信


public function index(){
//获得参数 signature nonce token timestamp echostr
$nonce     = $_GET['nonce'];
$token     = 'weixin';
$timestamp = $_GET['timestamp'];
$echostr   = $_GET['echostr'];
$signature = $_GET['signature'];
//形成数组,然后按字典序排序
$array = array();
$array = array($nonce, $timestamp, $token);
sort($array);
//拼接成字符串,sha1加密 ,然后与signature进行校验
$str = sha1( implode( $array ) );
if( $str  == $signature && $echostr ){
//第一次接入weixin api接口的时候
echo  $echostr;
exit;
}else{
$this->reponseMsg();
}
}


2.接受事件并回复:

//1.获取到微信推送过来post数据(xml格式)
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
//2.处理消息类型,并设置回复类型和内容
$postObj = simplexml_load_string( $postArr );

//判断是否订阅并回复多图文消息

if( strtolower( $postObj->MsgType) == 'event'){
//如果是关注 subscribe 事件
if( strtolower($postObj->Event == 'subscribe') ){
//回复用户消息(纯文本格式)
$arr = array(
array(
'title'=>'imooc',
'description'=>"欢迎来到慕课网---用户id:".$postObj->FromUserName,
'picUrl'=>'http://114.215.80.202/weixin/Public/head.jpg',
'url'=>'http://www.imooc.com',
)
);
$indexModel = D('Index');
$indexModel->responseSubscribe($postObj,$arr);

}

}

//回复多图文
public function responseMSG($postObj,$arr){
//return 1;
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;

$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($arr)."</ArticleCount>
<Articles>";

foreach($arr as $k=>$v){
$template .="<item>
<Title><![CDATA[".$v['title']."]]></Title> 
<Description><![CDATA[".$v['description']."]]></Description>
<PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
<Url><![CDATA[".$v['url']."]]></Url>
</item>";
}

$template .="</Articles></xml> ";
echo sprintf($template, $toUser, $fromUser, time(), 'news');
}

//回复文本
public function responseText($postObj,$content){
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
//注意模板中的中括号 不能少 也不能多
$fromUser = $postObj->ToUserName;
$toUser   = $postObj->FromUserName; 
$time     = time();
// $content  = '18723180099';
$msgType  = 'text';
echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值