天天看点

安卓接入微信php处理,微信公众平台开发者模式的接入-PHP

最近看了下 mp 的官方文档越写越晦涩了,模模糊糊的不知道想讲明什么,连最近本的消息接入 demo 都没了

如今虽然 sdk 很多 傻瓜式接入很方便 但多了解下明面的有利无弊

function checkSignature($token)

{

if (!isset($_GET["signature"]) || !isset($_GET["timestamp"]) || !isset($_GET["nonce"])) {

return false;

}

$signature = $_GET["signature"];

$timestamp = $_GET["timestamp"];

$nonce = $_GET["nonce"];

$tmp_arr = array($timestamp, $nonce, $token);

sort($tmp_arr, SORT_STRING);

$tmp_str = implode($tmp_arr);

$signature_local = sha1($tmp_str);

if ($signature == $signature_local) {

return true;

} else {

return false;

}

}

// 与公众平台约定的 token

CONST TOKEN = "big_cat";

// 接入开发者模式时 mp 发送的 echostr 的 GET 请求验证服务器是否合法

// signature=xxx&echostr=xxx&timestamp=xxx&nonce=xxx

// 成功接入后 后续的 wx 消息都会以 POST 请求的方式以如下的 url 发送数据

// signature=xxx&timestamp=xxx&nonce=xxx&openid=xxx

// 任何情况下都应首先验证消息的合法性

if (checkSignature(TOKEN) === true) {

if (isset($_GET['echostr'])) { // wechat 开启开发者模式接入时的认证

echo $_GET['echostr'];

} else {

$data_raw = file_get_contents("php://input");

//message_handler($data)

file_put_contents('wechat.log', $data_raw . PHP_EOL, FILE_APPEND);

}

}

验证消息请求的合法性

公众平台发起任何请求都会携带 signature timestamp nonce 三个 query string params

如果有 echostr 说明为开发者模式接入验证

否则为开发者模式接入后微信公众平台转发的用户消息或事件

任何情况下都要校验消息的合法性