Yii2.0 – 微信token验证
     发布在:PHP      浏览:64      评论:0 条评论

文件目录

Yii2.0 - 微信token验证

params.php

<?php
return [
    // 微信接入
    'wechat' => [
        'token' => '这里填写你的token',
    ],
];
?>

ValidController.php

<?php
namespace wechat\controllers;

use Yii;
use yii\helpers\Url;
use common\controllers\WechatController;

/**
 * 微信token验证
 */
class ValidController extends WechatController
{
    public function actionIndex()
    {
        $request = Yii::$app -> request;

        $echoStr = $request -> get('echostr', '');

        $signature = $request -> get('signature', '');

        $timestamp = $request -> get('timestamp', ''); 

        $nonce = $request -> get('nonce', ''); 

        //valid signature , option
        if ($this -> checkSignature($signature, $timestamp, $nonce) && $echoStr) {
            echo $echoStr;
        }
    }

    private function checkSignature($signature, $timestamp, $nonce)
    {
        // you must define TOKEN by yourself
        $token = Yii::$app->params['wechat']['token']; 

        if (!$token) {
            echo 'TOKEN IS NOT DEFINE!';
        } else {
            $tmpArr = [$token, $timestamp, $nonce];

            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING); 

            $tmpStr = sha1(implode($tmpArr)); 

            if ($tmpStr == $signature){
                return true;
            } else {
                return false;
            }
        }
    }
}
?>

微信公众平台

Yii2.0 - 微信token验证

原文链接:https://www.jianshu.com/p/8ebeb8ff6cee

Responses