Yii2微信开发系列一:接入微信

Yii2后台配置

1.在app/config/params.php中配置token参数

1
2
3
4
5
6
return [
//微信接入
'wechat' =>[
'token' => 'your token',
],
];

2.在app/config/main.php中配置路由

因为接口模块使用的RESTful API,所以需要定义路由规则。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'wechat',
'extraPatterns' => [
'GET valid' => 'valid',
],
],
],
],

3.在app/controllers中新建WechatController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php

namespace api\controllers;

use Yii;
use yii\rest\ActiveController;

class WechatController extends ActiveController
{


public $modelClass = '';

public function actionValid()
{

$echoStr = $_GET["echostr"];
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
//valid signature , option
if($this->checkSignature($signature,$timestamp,$nonce)){
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 defined!';
} else {
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

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

}

微信公众号后台配置

在微信公众号后台配置URL和Token,然后提交验证即可。

1
2
URL:http://app.demo.com/wechats/valid
Token:your token
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!