微信公众号开发之服务器配置(接口配置信息)

暂以申请的测试号为例:

1. 在params.php文件中填写微信的参数(必须跟服务器填写或生成的完全一致):

'wechatConfig' => [
    'app_id' => 'wxe04f591fa3c7cbe1',  // AppID
    'secret' => 'f41bc4a254360d85692c0fb517d12ada',  // AppSecret
    'token' => 'wxe04f591fa3c7cbe1',  // Token
],

2. 控制器(SiteController.php):

<?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!');
        }
    }
}

2.1 控制器中如果使用了动作过滤器,还要添加:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['login', 'error', 'wechat'],
                    'allow' => true,
                ],
                [
                    'actions' => ['logout', 'index'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
    ];
}

3.填写微信公众号的服务器配置: