Coder Social home page Coder Social logo

laravel-wechat's Introduction

EasyWeChat for Laravel

微信 SDK EasyWeChat for Laravel, 基于 w7corp/easywechat

Sponsor me

7.x 起不再默认支持 Lumen。

框架要求

  • overtrue/laravel-wechat:^7.0 -> Laravel >= 8.0
  • overtrue/laravel-wechat:^6.0 -> Laravel/Lumen >= 7.0
  • overtrue/laravel-wechat:^5.1 -> Laravel/Lumen >= 5.1

安装

composer require overtrue/laravel-wechat:^7.2

配置

  1. 创建配置文件:
php artisan vendor:publish --provider="Overtrue\\LaravelWeChat\\ServiceProvider"
  1. 可选,添加别名
'aliases' => [
    // ...
    'EasyWeChat' => Overtrue\LaravelWeChat\EasyWeChat::class,
],
  1. 每个模块基本都支持多账号,默认为 default

使用

🚨 在中间件 App\Http\Middleware\VerifyCsrfToken 排除微信相关的路由,如:

protected $except = [
    // ...
    'wechat',
];

对于 Laravel 11.x 可以使用bootstrap/app.php 中的$middleware->validateCsrfTokens方法:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        // ...
        'wechat',
    ]);
})

下面以接收普通消息为例写一个例子。

路由:

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

注意:一定是 Route::any, 因为微信服务端认证的时候是 GET, 接收用户消息时是 POST

然后创建控制器 WeChatController

<?php

namespace App\Http\Controllers;

use Log;

class WeChatController extends Controller
{
    public function serve()
    {
        Log::info('request arrived.'); 

        $server = app('easywechat.official_account')->getServer();

        $server->with(function($message){
            return "欢迎关注 overtrue!";
        });

        return $server->serve();
    }
}

OAuth 中间件

使用中间件的情况下 app/config/easywechat.php 中的 oauth.callback 就随便填写吧(因为用不着了 😄)。

  1. app/Http/Kernel.php 中添加路由中间件:
protected $routeMiddleware = [
    // ...
    'easywechat.oauth' => \Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate::class,
];
  1. 在路由中添加中间件:
//...
Route::group(['middleware' => ['web', 'easywechat.oauth']], function () {
    Route::get('/user', function () {
        $user = session('easywechat.oauth_user.default'); // 拿到授权用户资料

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

中间件支持指定配置名称:'easywechat.oauth:default',当然,你也可以在中间件参数指定当前的 scopes:

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

// 或者指定账户的同时指定 scopes:
Route::group(['middleware' => ['easywechat.oauth:default,snsapi_userinfo']], function () {
  // ...
});

上面的路由定义了 /user 是需要微信授权的,那么在这条路由的回调 或 控制器对应的方法里, 你就可以从 session('easywechat.oauth_user.default') 拿到已经授权的用户信息了。

模拟授权

有时候我们希望在本地开发完成后线上才真实的走微信授权流程,这将减少我们的开发成本,那么你需要做以下两步:

  1. 准备模拟授权资料:
use Illuminate\Support\Arr;
use Overtrue\Socialite\User as SocialiteUser;

$user = new SocialiteUser([
            'id' => 'mock-openid',
            'name' => 'overtrue',
            'nickname' => 'overtrue',
            'avatar' => 'http://example.com/avatars/overtrue.png',
            'email' => null,
            'original' => [],
            'provider' => 'WeChat',
        ]);

以上字段在 scope 为 snsapi_userinfo 时尽可能配置齐全哦,当然,如果你的模式只是 snsapi_base 的话只需要 openid 就好了。

  1. 将资料写入 session:

注意:一定要在调用 OAuth 中间件之前写入,比如你可以创建一个全局中间件来完成这件事儿,只在开发环境启用即可。

session(['easywechat.oauth_user.default' => $user]); // 同理,`default` 可以更换为您对应的其它配置名

事件

你可以监听相应的事件,并对事件发生后执行相应的操作。

  • OAuth 网页授权:Overtrue\LaravelWeChat\Events\WeChatUserAuthorized
// 该事件有以下属性
$event->user; // 同 session('easywechat.oauth_user.default') 一样
$event->isNewSession; // 是不是新的会话(第一次创建 session 时为 true)
$event->account; // 当前中间件所使用的账号,对应在配置文件中的配置项名称

开放平台支持

您可以适用内置的 Overtrue\LaravelWeChat\Traits\HandleOpenPlatformServerEvents 来快速完成开放平台的服务端验证工作:

routes/web.php:

Route::any('/open-platform/server', OpenPlatformController::class);

app/Http/Controllers/OpenPlatformController.php:

<?php

namespace App\Http\Controllers;

use Overtrue\LaravelWeChat\Traits\HandleOpenPlatformServerEvents;

class OpenPlatformController extends Controller
{
    use HandleOpenPlatformServerEvents;
    
    public function __invoke(Application $application): \Psr\Http\Message\ResponseInterface
    {
        $app = app('easywechat.open_platform');
        
        return $this->handleServerEvents($app);
    }
}

Tips: 默认会根据微信开放平台的推送内容触发如下事件,你可以监听相应的事件并进行处理:

  • 授权方成功授权:Overtrue\LaravelWeChat\Events\OpenPlatform\Authorized
  • 授权方更新授权:Overtrue\LaravelWeChat\Events\OpenPlatform\AuthorizeUpdated
  • 授权方取消授权:Overtrue\LaravelWeChat\Events\OpenPlatform\Unauthorized
  • 开放平台推送 VerifyTicket:Overtrue\LaravelWeChat\Events\OpenPlatform\VerifyTicketRefreshed
// 事件有如下属性
$message = $event->payload; // 开放平台事件通知内容

配置后 http://example.com/open-platform/server 则为开放平台第三方应用设置的授权事件接收 URL。

更多 SDK 的具体使用请参考:https://www.easywechat.com

❤️ Sponsor me

Sponsor me

如果你喜欢我的项目并想支持它,点击这里 ❤️

Project supported by JetBrains

Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.

PHP 扩展包开发

想知道如何从零开始构建 PHP 扩展包?

请关注我的实战课程,我会在此课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

License

MIT

laravel-wechat's People

Contributors

ac1982 avatar aufree avatar baijunyao avatar bangbangda avatar branchzero avatar dependabot-preview[bot] avatar dependabot[bot] avatar ekuwang avatar flutterbest avatar freyo avatar garveen avatar godruoyi avatar hellojinjie avatar hihuangwei avatar jellybool avatar jinchun avatar jxlwqq avatar lazyou avatar lonquan avatar milewski avatar mingyoung avatar overtrue avatar remxcode avatar renyang9876 avatar ruchengtang avatar skys215 avatar summerblue avatar tianyong90 avatar wuwx avatar wynsto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-wechat's Issues

服务器token验证

我的控制器:
public function serve()
{
Log::info('request arrived.'); # 注意:Log 为 Laravel 组件,所以它记的日志去 Laravel 日志看,而不是 EasyWeChat 日志
$wechat = app('wechat');
//return $wechat;
app('wechat')->server->setMessageHandler(function($message){
return "欢迎关注 overtrue!";
});
Log::info('return response.');
return app('wechat')->server->serve();
}
我的route:Route::any('/weixin', 'WeixinController@serve');
我的middle:
protected $except = [
'weixin',
];
我的报告:BadRequestException in Guard.php line 317:
Invalid request.
我的日记:所有参数key,id等传输正确
腾讯验证:token验证错误

微信支付统一下单结果只有一个false

根据文档执行到$result = $payment->prepare($order);后,
打印$result的值,一直是返回只有false:
Collection {#944
#items: array:1 [
0 => false
]
}
也没有任何提示错误?还没找到是什么原因

js支付创建订单一直失败

代码如下:

            $orderAttributes = [
                'trade_type' => 'JSAPI',
                'body' => '支付订单',
                'out_trade_no' => Carbon::now()->format('ymdHisU'),
                'total_fee' => bcmul($product->combo->price,100,0),
                'notify_url' => url('xxx'),
                'openid' => \Auth::user()->openid,
                'attach' => sprintf('PAPA_%s_%s',$product->id,bcmul($product->combo->price,100,0)),
                'device_info' => 'WEB',
                'spbill_create_ip' => '8.8.8.8'
            ];
            $order = new Order($orderAttributes);
            $result = $wechat->payment->prepare($order);var_dump($result);

输出:

object(EasyWeChat\Support\Collection)#323 (1) {
["items":protected]=>
array(1) {
[0]=>
bool(false)
}
}
远端 HTTP CODE 200。response body 为空

使用composer连接不上去

以下是我们运行的结果

Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package overtrue/laravel-wechat could not be found in any version, there may be a typo in the package name.
Problem 2
- laravel/framework v5.0.28 requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
- laravel/framework v5.0.28 requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
- Installation request for laravel/framework == 5.0.28.0 -> satisfiable by laravel/framework[v5.0.28].

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

laravel-debugbar兼容问题

文档里说 “如果你用了 laravel-debugbar,请禁用或者关掉,否则这模块别想正常使用!!!”,请问不能同时使用debugbar的原因是什么?

安装时出错

作者你好,我用composer安装时出现了以下问题,搜寻网上没有找到解决办法,请教如何解决

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install overtrue/laravel-wechat 3.0.1
- Conclusion: remove symfony/http-foundation v2.6.13
- Installation request for overtrue/laravel-wechat ~3.0 -> satisfiable by overtrue/laravel-wechat[3.0, 3.0.1].
- Conclusion: don't install symfony/http-foundation v2.6.13
- overtrue/laravel-wechat 3.0 requires overtrue/wechat ~3.0 -> satisfiable by overtrue/wechat[3.0, 3.0.1, 3.0.2, 3.0.3, 3.0.4].
- overtrue/wechat 3.0 requires overtrue/socialite ^1.0 -> satisfiable by overtrue/socialite[1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7].
- overtrue/wechat 3.0.1 requires overtrue/socialite ^1.0 -> satisfiable by overtrue/socialite[1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7].
- overtrue/wechat 3.0.2 requires overtrue/socialite >=1.0.7 -> satisfiable by overtrue/socialite[1.0.7].
- overtrue/wechat 3.0.3 requires overtrue/socialite >=1.0.7 -> satisfiable by overtrue/socialite[1.0.7].
- overtrue/wechat 3.0.4 requires overtrue/socialite >=1.0.7 -> satisfiable by overtrue/socialite[1.0.7].
- overtrue/socialite 1.0.0 requires symfony/http-foundation ~2.8|~2.7 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3].
- overtrue/socialite 1.0.1 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.2 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.3 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.4 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.5 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.6 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- overtrue/socialite 1.0.7 requires symfony/http-foundation ~2.8|~2.7|~3.0 -> satisfiable by symfony/http-foundation[v2.7.0, v2.7.1, v2.7.10, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.2, v2.8.3, v3.0.0, v3.0.1, v3.0.2, v3.0.3].
- Can only install one of: symfony/http-foundation[v2.7.0, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.1, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.10, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.2, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.3, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.4, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.5, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.6, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.7, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.8, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.7.9, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.8.0, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.8.1, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.8.2, v2.6.13].
- Can only install one of: symfony/http-foundation[v2.8.3, v2.6.13].
- Can only install one of: symfony/http-foundation[v3.0.0, v2.6.13].
- Can only install one of: symfony/http-foundation[v3.0.1, v2.6.13].
- Can only install one of: symfony/http-foundation[v3.0.2, v2.6.13].
- Can only install one of: symfony/http-foundation[v3.0.3, v2.6.13].
- Installation request for symfony/http-foundation == 2.6.13.0 -> satisfiable by symfony/http-foundation[v2.6.13].

composer update 之后报错

PHP Parse error: syntax error, unexpected '{' in /home/wwwroot/weixin.xxx.com/vendor/overtrue/laravel-wechat/src/ServiceProvider.php on line 62

关于协作开发的问题

最近发现一个问题。由于需要注册 ServiceProvider,导致一个问题。
即:最初引用本插件的开发者在config/app.php中注册了ServiceProvider,将代码提交到版本库后别的开发者更新下来,由于laravel默认是将vendor加入了git的忽略列表,因此其他开发者需要执行一次composer update才可能将插件安装,但是由于config/app.php已经注册了Overtrue\LaravelWechat\ServiceProvider,但此时Overtrue\LaravelWechat\ServiceProvider是不存在的,那么composer update将会报错,导致update无法执行。
对于这个问题,是否有更好的解决方案呢?

说明文档更新

在5.2中应该是,请更新readme谢谢
'Wechat' => Overtrue\LaravelWechat\Facade::class,

5.4 似乎不可用

local.ERROR: Overtrue\Socialite\AuthorizeFailedException: Authorize Failed: {"errcode":40013,"errmsg":"invalid appid, hints: [ req_id: tQPTEa0975s109 ]"} in /mnt/sdc/dindon_front/vendor/overtrue/socialite/src/Providers/AbstractProvider.php:409

Oauth 中间件, 网页授权的一直报这个错误。
如果直接使用 overtrue/wechat, 则会提示 secret 无效

请问一下微信的测试账号出现:该公众号暂时无法提供服务,请稍后再试

\x0A\x0A1429670043\x0A\x0A\x0A6140386078960211765\x0A" 500 12378 "-" "Mozilla/4.0" - "0.070,0.138" 网上说是: 请开发者注意,一旦遇到以下情况,微信都会在公众号会话中,向用户下发系统提示“该公众号暂时无法提供服务,请稍后再试”: 1、开发者在5秒内未回复任何内容 2、开发者回复了异常数据,比如JSON数据等 请问一下不知道是否是库本身原因还是微信这边的问题呢?

发送模板消息有问题

感谢作者贡献此库,之前一直node,现在发现PHP库发送模板消息有点问题:

  1. url是必填项,node是非必填的
  2. \n字符无效,node是有效的

这两个部分对我们现在的应用场景蛮重要的,请问下应该修改库的什么部分来修复这两个问题呢,多谢!

服务器验证问题

我用laravel 5.1.11的版本,在微信公众平台的服务器配置中,做服务器验证时总提示Token验证失败,验证要怎么操作,大神指教!!!!

下载素材的出错

$media->download($value, $filename);
下载素材时出现下面问题。

[2015-04-30 18:52:31] local.ERROR: exception 'Overtrue\Wechat\Exception' with message '[Wechat][43002] 43002 需要POST请求' in /var/www/meishenghuo/web/vendor/overtrue/wechat/src/Wechat/Http.php:91
Stack trace:
#0 /var/www/meishenghuo/web/vendor/overtrue/wechat/src/Wechat/Utils/Http.php(65): Overtrue\Wechat\Http->request('http://file.api...', 'GET', Array, Array)
#1 /var/www/meishenghuo/web/vendor/overtrue/wechat/src/Wechat/Media.php(251): Overtrue\Wechat\Utils\Http->get('http://file.api...', Array)
#2 /var/www/meishenghuo/web/app/Http/Controllers/RepairsController.php(104): Overtrue\Wechat\Media->download('Gr31ecyJCdFhQK2...', '/var/www/meishe...')

Class wechat.server does not exist

Class wechat.server does not exist
很奇怪,其他都使用.唯独"wechat.server"提示不存在.

将下面代码,写到自带的"App\Providers\AppServiceProvider"却能使用.

$this->app->singleton(['Overtrue\\Wechat\\Server' => 'wechat.server'], function($app){
    return new WechatServer(config('wechat.app_id'), config('wechat.token'), config('wechat.encoding_key'));
});

这是为什么???

请问为什么取不到$wechat呢

$wechat = App::make('wechat');
$wechat->on('message', ...);

在laravel 5 中报错 :[2015-04-19 03:19:04] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Undefined class constant 'User'' in /var/www/wechat/app/Http/Controllers/WechatController.php:22

请问这是为什么呢?

使用微信对账单下载时候报错

php 版本:5.5.30
"overtrue/laravel-wechat":版本:3.0.6

使用微信对账单下载时候报错
$result=$payment->downloadBill(intval($request->input('date')));

ErrorException in XML.php line 37: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found

in XML.php line 37
at HandleExceptions->handleError('2', 'simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '&lt;' not found', '/www/wwwroot/laravel/vendor/overtrue/wechat/src/Support/XML.php', '37', array('xml' => object(Stream)))
at simplexml_load_string('交易时间,公众账号ID,商户号,子商户号,设备号,微信订单号,商户订单号,用户标识,交易类型,交易状态,付款银行,货币种类,总金额,企业红包金额,微信退款单号,商户退款单号,退款金额,企业红包退款金额,退款类型,退款状态,商品名称,商户数据包,手续费,费率 `2016-03-14

关于在CSRF中排除微信路由的做法疑问

看到你文档写的做微信开发的时候必须要在CSRF验证中去除微信的路由,但是这样做我在测试中发现在Laravel5.2版本中是有问题的,原因如下:
根据Laravel文档我们可以设置$excerpt属性来排除部分不需要csrf的路由,但是我实际测试发现设置了也没用。查看csrf的源码如下:

public function handle($request, Closure $next)
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

从以上源码可以看到,if条件中四个只要满足一个就会执行这个中间件,第一个$this->isReading方法的源码:

protected function isReading($request)
    {
        return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
    }

可以看到如果是HEAD,GET,OPTIONS请求方法就不会执行$this->shouldPassThrough这个方法来判定当前是否需要过CSRF中间件了。而且微信是GET和POST请求都有,所以我觉得在csrf中排除微信相关的路由这个做法有点不适合,你觉得呢?

Laravel5.3下应该如何在路由中添加中间件呢?

在路由中添加中间件:
5.2是这样的,5.3的路由该如何配置呢?
以 5.2 为例:

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

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

Illegal offset type in unset with Laravel 5.4

Laravel->5.4 fresh installed.
Laravel->wechat 3.2.4.
Project crashed if add Overtrue\LaravelWechat\ServiceProvider::class to providers array.

    [ErrorException]
    Illegal offset type in unset

Config is not loaded by default

Hello,

I'm trying to seta OAuth with WeChat on my app.
It seems the config file was not loaded, let see :

In the OAuthAuthenticate middleware, in the handle() function, you create a new $wechat like this :

$wechat = app('EasyWeChat\\Foundation\\Application');

But this error was thrown :

Unresolvable dependency resolving [Parameter #0 [ <required> $config ]] in class EasyWeChat\Foundation\Application

If I set the default param to empty array, and load the config file after like this :

public function __construct($config)
    {
        parent::__construct();
        $config = config('wechat');

        $this['config'] = function () use ($config) {
            return new Config($config);
        };

        if ($this['config']['debug']) {
            error_reporting(E_ALL);
        }

        $this->registerProviders();
        $this->registerBase();
        $this->initializeLogger();

        Log::debug('Current configuration:', $config);
    }

It works well.

PR was made : #30

中间件授权 40001

使用中间件授权的方式。

某些手机授权不成功,拿不到openid.

user对象:

{
  "id": null,
  "name": null,
  "nickname": null,
  "avatar": null,
  "email": null,
  "original": {
    "errcode": 40001,
    "errmsg": "invalid credential, access_token is invalid or not latest, hints: [ req_id: aGWfma0000ns83 ]"
  },
  "token": {
    "access_token": "p5rApFmJHpEzw37UIlwQNMnTMCxzksyrnp1fQGbcAxhCfrH5wGqFHI84SF6dDHhPCMs6J9DITF2br6gOxEEY2Hkzuw5qPjSnnuoK5uiw1zo",
    "expires_in": 7200,
    "refresh_token": "W9OZ31vZK0r5gCeMWiEOgXac-d23-CQZ3dBteZ93XWiqUAxgei9R9swNUKtYqdc9B9Zr98olV35LDsyaHoOwPxsHm61a-S7xW1WfIE8-NX0",
    "openid": "oN-UTxF1XDoe-cs2MxUfedxUdX2Q",
    "scope": "snsapi_userinfo"
  }
}

通过alias方式获取实例发生exception

具体配置
config providers:
Overtrue\LaravelWechat\ServiceProvider::class,

alias:
'Wechat' => Overtrue\LaravelWechat\Facade::class,

代码:
$wechat = Wechat::server();
$payment = $wechat->payment;

异常情况:
2016-07-24 22 05 55

如果在回调方法里使用 Model::create() 函数,就会报异常

大神你好
实例

//收到订阅事件
 $server->on('event','subscribe',function($event){
            $openID = $event->FromUserName;
            $weChatUser = Wechat::user();
            $userInfo = $weChatUser->get($openID)->toArray();
            Users::create($userInfo);
           return Message::make('text')->content('欢迎关注');
)}

就会报错:

FatalErrorException in Response.php line 0:
Method Overtrue\Wechat\Server::__toString() must not throw an exception

经过各种测试,只要是使用 Model::create() 方法就会这样, 在消息接收里也是这样。
我的Laravel 版本是 5.1
实在解决不了了,不知道哪里出的错。大神帮帮忙啊,多谢~~

似乎Facade不起作用

Hi, 我按照手册引入了相关的provider和facade。但是在controller中使用Wechat::时,报找不到相关的类。很迷惑哟~

微信公众号动态配置无效

微信公众号动态配置无效....
//
$wechatConfig = DB::table('wx_config')->first();
//...
//
$wechat = app('wechat', $wechatConfig);

$wechat['config']的值仍是config/wechat.php配置文件中的值,并不是传过去的$wechatConfig

当使用 Laravel cache 时,verify ticket 无法缓存

如题,我看过代码,原因应该是VerifyTicket 的 cache 的 save() 方法没有给时间,即为 0,而 Laravel 的cache 的 put 方法是不考虑是不是 0 的,必须用 forever 方法。代码片段都在下面供参考。
测试过 database 和 redis 两个 cache driver。

VerifyTicket

    public function cache(Collection $message)
    {
        return $this->getCache()->save(
            $this->getCacheKey(),
            $message->get($this->ticketXmlName)
        );
    }

DatabaseStore

    public function put($key, $value, $minutes)
    {
        $key = $this->prefix.$key;

        // All of the cached values in the database are encrypted in case this is used
        // as a session data store by the consumer. We'll also calculate the expire
        // time and place that on the table so we will check it on our retrieval.
        $value = $this->encrypter->encrypt($value);

        $expiration = $this->getTime() + (int) ($minutes * 60);

        try {
            $this->table()->insert(compact('key', 'value', 'expiration'));
        } catch (Exception $e) {
            $this->table()->where('key', $key)->update(compact('value', 'expiration'));
        }
    }

    public function forever($key, $value)
    {
        $this->put($key, $value, 5256000);
    }

RedisStore

    public function put($key, $value, $minutes)
    {
        $this->connection()->setex(
            $this->prefix.$key, (int) max(1, $minutes * 60), $this->serialize($value)
        );
    }

    public function forever($key, $value)
    {
        $this->connection()->set($this->prefix.$key, $this->serialize($value));
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.