PHP code example of barretzhi / laravel-wechat

1. Go to this page and download the library: Download barretzhi/laravel-wechat library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

barretzhi / laravel-wechat example snippets


  Overtrue\LaravelWeChat\ServiceProvider::class,
  

  'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,
  

  $app->register(Overtrue\LaravelWeChat\ServiceProvider::class);
  

Route::any('/wechat', 'WeChatController@serve');



namespace App\Http\Controllers;

use Log;

class WeChatController extends Controller
{

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意:Log 为 Laravel 组件,所以它记的日志去 Laravel 日志看,而不是 EasyWeChat 日志

        $app = app('wechat.official_account');
        $app->server->push(function($message){
            return "欢迎关注 overtrue!";
        });

        return $app->server->serve();
    }
}



namespace App\Http\Controllers;

use EasyWeChat\OfficialAccount\Application;

class WechatController extends Controller
{

    public function demo(Application $officialAccount)
    {
        // $officialAccount 则为容器中 EasyWeChat\OfficialAccount\Application 的实例
    }
}

'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,

  $officialAccount = EasyWeChat::officialAccount(); // 公众号
  $work = EasyWeChat::work(); // 企业微信
  $payment = EasyWeChat::payment(); // 微信支付
  $openPlatform = EasyWeChat::openPlatform(); // 开放平台
  $miniProgram = EasyWeChat::miniProgram(); // 小程序


protected $routeMiddleware = [
    // ...
    'wechat.oauth' => \Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate::class,
];

//...
Route::group(['middleware' => ['web', 'wechat.oauth']], function () {
    Route::get('/user', function () {
        $user = session('wechat.oauth_user'); // 拿到授权用户资料

        dd($user);
    });
});

Route::group(['middleware' => ['web', 'wechat.oauth:snsapi_userinfo']], function () {
  // ...
});

/*
 * 开发模式下的免授权模拟授权用户资料
 *
 * 当 enable_mock 为 true 则会启用模拟微信授权,用于开发时使用,开发完成请删除或者改为 false 即可
 */
'enable_mock' => env('WECHAT_ENABLE_MOCK', true),
'mock_user' => [
    'openid' => 'odh7zsgI75iT8FRh0fGlSojc9PWM',
    // 以下字段为 scope 为 snsapi_userinfo 时需要
    'nickname' => 'overtrue',
    'sex' => '1',
    'province' => '北京',
    'city' => '北京',
    'country' => '中国',
    'headimgurl' => 'http://wx.qlogo.cn/mmopen/C2rEUskXQiblFYMUl9O0G05Q6pKibg7V1WpHX6CIQaic824apriabJw4r6EWxziaSt5BATrlbx1GVzwW2qjUCqtYpDvIJLjKgP1ug/0',
],

// 该事件有两个属性
$event->user; // 同 session('wechat.oauth_user') 一样
$event->isNewSession; // 是不是新的会话(第一次创建 session 时为 true)

// 开放平台事件有如下属性
$message = $event->message;     // 获取授权事件通知内容
shell
  php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"