在ThinkPHP中实现微信公众号自定义菜单下发扫码推事件消息卡片功能,可以按照以下步骤:
-
在微信公众平台设置自定义菜单,并将菜单中某个按钮的类型设置为“扫码推事件”。
-
在ThinkPHP中编写相应的控制器和方法来处理用户点击菜单的事件,示例代码如下:
public function scan()
{
$postStr = file_get_contents("php://input");
$postObj = simplexml_load_string($postStr, "SimpleXMLElement", LIBXML_NOCDATA);
$eventKey = trim($postObj->EventKey);
$eventKey = str_replace("qrscene_", "", $eventKey);
//根据 $eventKey 做相应的业务逻辑处理
//生成相应的卡片消息
$card = array(
"touser" => $postObj->FromUserName,
"msgtype" => "wxcard",
"wxcard" => array(
"card_id" => "card_id",
"card_ext" => array(
"code" => $eventKey,
"openid" => $postObj->FromUserName,
),
),
);
$result = $this->wechat->sendCustomMessage($card);
//根据 $result 的值判断消息是否发送成功
}
- 在上述代码中,使用了第三方扩展库 EasyWeChat 来发送自定义消息。需要先引入 EasyWeChat,并初始化 Wechat 对象。
use EasyWeChatFoundationApplication;
$options = [
"debug" => true,
"app_id" => "your-app-id",
"secret" => "your-app-secret",
"token" => "your-token",
"aes_key" => "your-aes-key",
];
$app = new Application($options);
$this->wechat = $app->wechat;
- 在生成卡片消息时,需要将扫码得到的信息作为卡片的扩展字段,以便后续业务逻辑的处理。生成卡片消息的代码示例如下:
$card = array(
"touser" => $postObj->FromUserName,
"msgtype" => "wxcard",
"wxcard" => array(
"card_id" => "card_id",
"card_ext" => array(
"code" => $eventKey,
"openid" => $postObj->FromUserName,
),
),
);
- 最后,调用 Wechat 对象的 sendCustomMessage 方法来发送卡片消息,并根据返回结果判断消息是否发送成功。
完整代码示例如下:
use EasyWeChatFoundationApplication;
class WechatController extends Controller
{
protected $wechat;
public function index()
{
$app_id = "your-app-id";
$app_secret = "your-app-secret";
$token = "your-token";
$encoding_aes_key = "your-aes-key";
$options = [
"debug" => true,
"app_id" => $app_id,
"secret" => $app_secret,
"token" => $token,
"aes_key" => $encoding_aes_key,
];
$app = new Application($options);
$this->wechat = $app->wechat;
$this->wechat->server->setMessageHandler([$this, "handleMessage"]);
$response = $this->wechat->server->serve();
$response->send();
}
public function handleMessage($message)
{
switch ($message->MsgType) {
case "event":
return $this->handleEvent($message);
default:
return "收到消息";
}
}
public function handleEvent($message)
{
switch ($message->Event) {
case "SCAN":
return $this->handleScan($message);
default:
return "收到事件";
}
}
public function handleScan($message)
{
$eventKey = trim($message->EventKey);
$eventKey = str_replace("qrscene_", "", $eventKey);
//根据 $eventKey 做相应的业务逻辑处理
//生成相应的卡片消息
$card = array(
"touser" => $message->FromUserName,
"msgtype" => "wxcard",
"wxcard" => array(
"card_id" => "card_id",
"card_ext" => array(
"code" => $eventKey,
"openid" => $message->FromUserName,
),
),
);
$result = $this->wechat->sendCustomMessage($card);
//根据 $result 的值判断消息是否发送成功
}
}