1. A previous colleague’s implementation downloaded the WeChat sample code, added it to the current application’s /vender/wx_biz_msg_crypt directory, and then used require in the init() method. See Figure 1.

<?php
namespace frontend\controllers;
use Yii;
use frontend\models\http\wx_auth\AccessToken as HttpWxAuthAccessToken;
use WXBizMsgCrypt;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
class WxMsgEventController extends Controller
{
public $redis;
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
public function init()
{
parent::init();
require __DIR__ . '/../vendor/wx_biz_msg_crypt/wxBizMsgCrypt.php';
$this->redis = Yii::$app->redis;
}
}
2. Searching GitHub for “WeChat encryption and decryption” yielded no official WeChat Git package, confirming that it cannot be installed via Composer.
3. Refer to Working with Third-Party Code, Using Downloaded Libraries: https://www.yiiframework.com/doc/guide/2.0/zh-cn/tutorial-yii-integration#using-downloaded-libs.
4. Reference: https://github.com/PizzaLiu/PHP-FIG/blob/master/PSR-4-autoloader-cn.md. Example: \Aura\Web\Response\Status. I decided to adjust the class library naming convention to comply with the PSR-4 standard, and then use Yii’s official autoloader to automatically load these classes. I renamed the file names to match their class names respectively, keeping the letter case consistent.
5. Edit the file: /frontend/vendor/src/wx-biz-msg-crypt/WXBizMsgCrypt.php, declare the namespace: wx\biz\msg\crypt, and delete all include_once statements. Apply the same process to the other files.
<?php
namespace wx\biz\msg\crypt;
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
/**
* 1.第三方回复加密消息给公众平台;
* 2.第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。
*/
class WXBizMsgCrypt
{
}6. It is important to note that the file PKCS7Encoder.php contains 2 classes, which need to be split into two files: PKCS7Encoder.php and Prpcrypt.php. The base directory name is in lowercase letters separated by hyphens. See Figure 2.

7. Declare a root path alias for the root namespace by editing the application configuration file: /frontend/config/main.php. The namespace prefix is in lowercase letters separated by forward slashes.
return [
'aliases' => [
'@wx/biz/msg/crypt' => '@frontend/vendor/wx-biz-msg-crypt/src',
],
]
8. Edit the previous colleague’s implementation file again to adjust the references: use wx\biz\msg\crypt\WXBizMsgCrypt;, and then remove the require statement from the init() method.
<?php
namespace frontend\controllers;
use Yii;
use frontend\models\http\wx_auth\AccessToken as HttpWxAuthAccessToken;
use wx\biz\msg\crypt\WXBizMsgCrypt;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
class WxMsgEventController extends Controller
{
public $redis;
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
public function init()
{
parent::init();
$this->redis = Yii::$app->redis;
}
/**
* 获取验证票据(接收微信服务器推送)
*/
public function actionTicket()
{
//try {
$request = Yii::$app->request;
$requestRawBody = $request->getRawBody();
$requestQueryParams = $request->getQueryParams();
file_put_contents(Yii::getAlias('@runtime') . '/componentVerifyTicketQueryParams.txt', print_r($requestQueryParams, true), LOCK_EX);
file_put_contents(Yii::getAlias('@runtime') . '/componentVerifyTicketRawBody.txt', print_r($requestRawBody, true), LOCK_EX);
$appId = Yii::$app->params['wxOpen']['component']['appId'];
$appSecret = Yii::$app->params['wxOpen']['component']['appSecret'];
$token = Yii::$app->params['wxOpen']['component']['token'];
$encodingAesKey = Yii::$app->params['wxOpen']['component']['symmetricKey'];
$msg = '';
$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
// 解密 xml 数据
$errCode = $pc->decryptMsg($requestQueryParams['msg_signature'], $requestQueryParams['timestamp'], $requestQueryParams['nonce'], $requestRawBody, $msg);
file_put_contents(Yii::getAlias('@runtime') . '/componentVerifyTicketDecrypt.txt', print_r($errCode, true), LOCK_EX);
// 解密成功
if ($errCode == 0) {
$ticketData = $this->xmlToArray($msg);
if (isset($ticketData['ComponentVerifyTicket'])) {
$redisCommandkeyPrefix = Yii::$app->params['redisCommand']['keyPrefix'];
$componentVerifyTicketKey = $redisCommandkeyPrefix . $ticketData['AppId'] . ':component_verify_ticket';
$this->redis->set($componentVerifyTicketKey, $ticketData['ComponentVerifyTicket']);
// 获取第三方平台component_access_token
$this->getComponentAccessToken($appId, $appSecret);
}
}
file_put_contents(Yii::getAlias('@runtime') . '/componentVerifyTicketMsgXml.txt', print_r($msg, true), LOCK_EX);
/*
} catch (\Throwable $th) {
file_put_contents(Yii::getAlias('@runtime') . '/componentVerifyTicketError.txt', print_r($th->getMessage(), true), LOCK_EX);
}
*/
exit('success');
}
9. Change the encoding of all files to UTF-8. Rerun the program and check the decrypted data file: componentVerifyTicketMsgXml.txt. The result meets expectations. See Figure 3.

<xml><AppId><![CDATA[wxd98c58b273d21bdf]]></AppId>
<CreateTime>1625124291</CreateTime>
<InfoType><![CDATA[component_verify_ticket]]></InfoType>
<ComponentVerifyTicket><![CDATA[ticket@@@PaPM2hcjK8DPPkW_ZzbaR4DCQtirExq932-BBnxhQg19QWJtIKm3Io0TXsWMqcdv-18WnjkWSiSLNPSoXmqGSA]]></ComponentVerifyTicket>
</xml>