laravel使用easywechat
官方文档:https://www.easywechat.com/docs/4.x/overview
安装插件
# Laravel < 5.8 composer require "overtrue/laravel-wechat:~4.0" # Laravel >= 5.8 composer require "overtrue/laravel-wechat:~5.0"
composer dump-autoload -o
push配置
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
增加.env配置公众号设置
WECHAT_OFFICIAL_ACCOUNT_APPID=wx78ae5bb2XXXX WECHAT_OFFICIAL_ACCOUNT_SECRET=214f1ce332XXXX WECHAT_OFFICIAL_ACCOUNT_TOKEN=yishXXX WECHAT_OFFICIAL_ACCOUNT_AES_KEY=6lwDoXXXXXFDFEEEEEEEEE
微信公众号接口配置信息
需要注意的是URL只能是80端口,对应代码:
路由:
Route::any('/','WechatController@valid');//
控制器方法
//验证签名 public static function valid() { // Log::info('request arrived'); $app = app('wechat.official_account'); $app->server->push(function($message){ return "欢迎关注"; }); return $app->server->serve(); }
若要设置用户授权菜单等需要在公众号设置
否则会出现
控制器示例:
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Log; class WechatController extends Controller { /**获取openid * Author Allen * DateTime 2021-03-12 * return [type] [description] */ public static function getOpenid() { $request = request()->all(); $validator = \Validator::make($request,[ 'code' => 'required', ],[ 'code.required' => '缺少code', ]); if($validator->fails()){ $error = $validator->errors()->all()[0]; return response()->json(['code' => 600, 'msg' => $error]); } $app = app('wechat.official_account'); $result = $app->oauth->getAccessToken($request['code']); if (!isset($result->openid)) { return response()->json(['code' => 600, 'msg' => '获取微信用户信息失败','result'=>$result]); } $openid=$user->openid; // dd($openid); // Log::info('request arrived'); return $openid; } //验证签名 public static function valid() { // Log::info('request arrived'); $app = app('wechat.official_account'); $app->server->push(function($message){ return "欢迎关注"; }); return $app->server->serve(); } /**菜单创建 * Author Allen * DateTime 2021-03-12 * return [type] [description] */ public static function menuCreate() { $app = app('wechat.official_account'); $buttons = [ [ "name" => "事务管理", "sub_button" => [ [ "type" => "view", "name" => "事务管理", "url" => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('wechat.official_account.default.app_id') . "&redirect_uri=" . urlencode('http://127.0.0.1/wechat/index') . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", ], ], ], ]; $app->menu->create($buttons); // $app->menu->delete(); // $list = $app->menu->list(); // $current = $app->menu->current(); // var_dump(json_encode($list,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ); // Log::info('request arrived'); return "创建成功"; } }