1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| <?php namespace Wx\Controller; use Wx\Controller\AppBaseController; class IndexController extends Controller { protected $wxCrypt;
public function index() { $echostr = I("get.echostr"); if (empty($echostr)) { $this->getWxCrypt(C('NEWENCODINGAESKEY')); $this->responseMsg(); }else{ $this->valid(); } }
private function valid() { $echoStr = I("get.echostr"); $signature = I("get.signature"); $timestamp = I("get.timestamp"); $nonce = I("get.nonce"); $tmpArr = array(C('TOKEN'), $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if($tmpStr == $signature){ echo $echoStr; exit; } }
private function responseMsg() { $postData = $GLOBALS["HTTP_RAW_POST_DATA"]; $msg = ''; $errCode = $this->wxCrypt->decryptMsg(I("get.msg_signature"), I("get.timestamp"), I("get.nonce"), $postData, $msg); if ($errCode != 0) { $this->getWxCrypt(C('OLDENCODINGAESKEY')); $errCode = $this->wxCrypt->decryptMsg(I("get.msg_signature"), I("get.timestamp"), I("get.nonce"), $postData, $msg); if ($errCode != 0) { print("解密失败: ".$errCode . "\n"); exit(); } }
if (!empty($msg)){ $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA); $MsgType = trim($postObj->MsgType);
switch ($MsgType) { case "text": $result = $this->receiveText($postObj); break; default: $result = "unknown msg type: ".$MsgType; break; } echo $result; }else { echo ""; exit; } }
private function receiveText($object) { $keyword = trim($object->Content); $content = "这是个文本消息";
$result = $this->transmitText($object, $content); return $result; }
private function transmitText($object, $content) { if (!isset($content) || empty($content)){ return ""; }
$xmlTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>"; $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content); $encryptMsg = ''; $errCode = $this->wxCrypt->encryptMsg($result, time(), $object->nonce, $encryptMsg); if ($errCode != 0) { print("加密后: " . $encryptMsg . "\n"); }
return $encryptMsg; }
private function getWxCrypt($encodingAESKey) { import('Vendor.Weixin.WXBizMsgCrypt'); $this->wxCrypt = new \WXBizMsgCrypt(C('TOKEN'), $encodingAESKey, C('APPID')); } }
|