$fromUsername = $data['FromUserName'];
$toUsername = $data['ToUserName'];
$msgType = trim($data['MsgType']);
//默认返回
$sendtime = time();
$sendtextTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
第一步:
if($toUsername == "gh_3c884a361561")
{
$sendMsgType = "text";
$sendContentStr = $event."from_callback";
$sendResultStr = sprintf($sendtextTpl, $fromUsername, $toUsername, $sendtime, $sendMsgType, $sendContentStr);
$encryptMsg = $this->encode_msg($sendResultStr, $timeStamp, $nonce, $encryptMsg);
return $encryptMsg;
}
第二步:
$keyword = trim($data['Content']);
if($toUsername == "gh_3c884a361561" && $keyword == "TESTCOMPONENT_MSG_TYPE_TEXT")
{
$sendMsgType = "text";
$sendContentStr = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
$sendResultStr = sprintf($sendtextTpl, $fromUsername, $toUsername, $sendtime, $sendMsgType, $sendContentStr);
$encryptMsg = $this->encode_msg($sendResultStr, $timeStamp, $nonce, $encryptMsg);
return $encryptMsg;
}
第三步:
if($toUsername == "gh_3c884a361561" && strpos($keyword, "QUERY_AUTH_CODE") > -1)
{
$ticket = str_replace("QUERY_AUTH_CODE:", "", $keyword);
include_once "wxAuthLib.php";
$wxAuthLib = new wxAuthLib();
$res = $wxAuthLib->getAuthorizationAppid($ticket); //使用授权码换取公众号的接口调用凭据和授权信息
//$this->helper->set_php_file(dirname(__FILE__)."/test.php", json_encode($res));
if($res != "")
{
$authorizer_access_token = $res['authorization_info']['authorizer_access_token'];
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
$curlPost['touser'] = $fromUsername;
$curlPost['msgtype'] = "text";
$curlPost['text']['content'] = $ticket."_from_api";
$curlPost = json_encode($curlPost);
$res = json_decode($this->helper->httpPost($curlPost, $url), true);
//$this->helper->set_php_file(dirname(__FILE__)."/test.php", $authorizer_access_token);
}
return "";
}
在发布之前首先需要完成整个授权流程,前2步发送的信息都需要加密发送。