Codeigniter-3-with-EasyWeChat

EasyWeChat 是什么

EasyWeChat 是一个开源的 微信 非官方 SDK。

EasyWeChat 的安装非常简单,因为它是一个标准的 Composer 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。

GitHub 源码地址:https://github.com/overtrue/wechat

环境需求

  • PHP >= 5.5.9
  • openssl 拓展
  • fileinfo 拓展(素材管理模块需要用到)

示例代码地址

https://github.com/Yhif/Codeigniter-3-with-EasyWeChat

进入正题,配置 Composer 路径

由于EasyWeChat是一个标准的 Composer 包,我们需要对 Codeigniter 3 增加对 Composer 支持。

首先在入口文件index.php中require_once BASEPATH.’core/CodeIgniter.php’;之前添加

1
2
3
4
5
6
7
8
9
10
// COMPOSER DIRECTORY NAME
// $composer_path = 'vendor';

// if (($_composer_temp = realpath($composer_path)) !== FALSE)
// {
// $composer_path = $_composer_temp.DIRECTORY_SEPARATOR;
// }

// Path to the composer directory
// define('COMPOSERPATH', $composer_path);

然后修改application/config/config.php文件中 Composer 自动加载路径为:

1
// $config['composer_autoload'] = COMPOSERPATH . 'autoload.php';


更新

然后修改application/config/config.php文件中 Composer 自动加载路径为:

1
$config['composer_autoload'] = FCPATH . 'vendor/autoload.php';


安装 EasyWeChat Composer 包

将原来的 composer.json 重命名 composer.json.bak, 执行

require "overtrue/wechat"```,等待安装完毕就可以优雅的使用 EasyWeChat 了。
1
2
3
4
5
6
7

**验证服务器地址有效性**

微信开发者中心配置就不说了,自己查看文档配置即可。
> http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html

覆盖 **application/controllers/Welcome.php** 文件为:

<?php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

use EasyWeChat\Foundation\Application;

class Welcome extends CI_Controller {

public function index()
{
    $this->load->view('welcome_message');
}

public function server()
{
    $options = [
        'debug'  => true,
        'app_id' => 'wxxxxxxxxxxxxxxxxxx',
        'secret' => 'f77xxxxxxxxxxxxxxxxxxxxx',
        'token'  => 'xxxxxxxx',
        'aes_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 可选
        'log' => [
            'level' => 'debug',
            'file'  => '/tmp/easywechat.log', // XXX: 绝对路径!!!!
        ]
    ];

    $app = new Application($options);
    // 从项目实例中得到服务端应用实例。
    $server = $app->server;
    $server->setMessageHandler(function ($message) {
        // $message->FromUserName // 用户的 openid
        // $message->MsgType // 消息类型:event, text....
        return "您好!欢迎关注我!";
    });
    $response = $server->serve();
    $response->send();
}

}

```

更多功能使用请查看 EasyWeChat 官方文档

文档:https://easywechat.org/zh-cn/docs/