PHP code example of duan617 / laravel-wechat
1. Go to this page and download the library: Download duan617/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/ */
duan617 / laravel-wechat example snippets
'providers' => [
// ...
Overtrue\LaravelWeChat\ServiceProvider::class,
],
'aliases' => [
// ...
'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,
],
$app->register(Overtrue\LaravelWeChat\ServiceProvider::class);
protected $except = [
// ...
'wechat',
];
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();
}
}
$officialAccount = \EasyWeChat::officialAccount(); // 公众号
$work = \EasyWeChat::work(); // 企业微信
$payment = \EasyWeChat::payment(); // 微信支付
$openPlatform = \EasyWeChat::openPlatform(); // 开放平台
$miniProgram = \EasyWeChat::miniProgram(); // 小程序
// 均支持传入配置账号名称
\EasyWeChat::officialAccount('foo'); // `foo` 为配置文件中的名称,默认为 `default`
//...
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.default'); // 拿到授权用户资料
dd($user);
});
});
Route::group(['middleware' => ['wechat.oauth:snsapi_userinfo']], function () {
// ...
});
// 或者指定账户的同时指定 scopes:
Route::group(['middleware' => ['wechat.oauth:default,snsapi_userinfo']], function () {
// ...
});
use Illuminate\Support\Arr;
use Overtrue\Socialite\User as SocialiteUser;
$user = new SocialiteUser([
'id' => Arr::get($user, 'openid'),
'name' => Arr::get($user, 'nickname'),
'nickname' => Arr::get($user, 'nickname'),
'avatar' => Arr::get($user, 'headimgurl'),
'email' => null,
'original' => [],
'provider' => 'WeChat',
]);
session(['wechat.oauth_user.default' => $user]); // 同理,`default` 可以更换为您对应的其它配置名
// 该事件有以下属性
$event->user; // 同 session('wechat.oauth_user.default') 一样
$event->isNewSession; // 是不是新的会话(第一次创建 session 时为 true)
$event->account; // 当前中间件所使用的账号,对应在配置文件中的配置项名称
'open_platform' => [
'uri' => 'serve',
'action' => Overtrue\LaravelWeChat\Controllers\OpenPlatformController::class,
'attributes' => [
'prefix' => 'open-platform',
'middleware' => null,
],
],
// 事件有如下属性
$message = $event->payload; // 开放平台事件通知内容
shell
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"