暂以申请的测试号为例:
'wechatConfig' => [ 'app_id' => 'wxe04f591fa3c7cbe1', // AppID 'secret' => 'f41bc4a254360d85692c0fb517d12ada', // AppSecret 'token' => 'wxe04f591fa3c7cbe1', // Token ],
<?php namespace frontend\controllers; use Yii; use yii\base\InvalidConfigException; use yii\web\Controller; use yii\web\NotFoundHttpException; class SiteController extends Controller { public $enableCsrfValidation = false; /** * 微信接口 * @return string * @throws InvalidConfigException * @throws NotFoundHttpException */ public function actionWechat() { $request = Yii::$app->request; switch($request->getMethod()){ case 'GET': if(self::checkSignature($request->get('signature'), $request->get('timestamp'), $request->get('nonce'))){ echo $request->get('echostr'); exit(); }else{ throw new NotFoundHttpException('签名验证失败.'); } break; case 'POST': // 处理消息回复 break; default: throw new NotFoundHttpException('所请求的页面不存在.'); } exit(); } /** * 参数校验 * @param string $signature * @param int $timestamp * @param int $nonce * @return bool * @throws InvalidConfigException */ private function checkSignature($signature, $timestamp, $nonce) { $token = Yii::$app->params['wechatConfig']['token']; if($token){ $tmpArr = [$token, $timestamp, $nonce]; sort($tmpArr, SORT_STRING); $newSignature = sha1(implode($tmpArr)); return $newSignature == $signature; }else{ throw new InvalidConfigException('TOKEN is not defined!'); } } }
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login', 'error', 'wechat'], 'allow' => true, ], [ 'actions' => ['logout', 'index'], 'allow' => true, 'roles' => ['@'], ], ], ], ]; }