准备工作:
1、已认证的服务号(apppid、appsecret、token、aes_key)
2、安全域名
3、已经用composer安装好easywechat
1、config/app.php 的 providers 数组,不用多说
'providers' => [
// ...
Overtrue\LaravelWeChat\ServiceProvider::class,
],
'aliases' => [
// ...
'EasyWeChat' => Overtrue\LaravelWeChat\Facade::class,
],
2、发布资源
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
3、相关配置 config/wechat.php
'official_account' => [
'default' => [
'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', '**'), // AppID
'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', '**'), // AppSecret
'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN', '**'), // Token
'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY', '**'), // EncodingAESKey
'oauth' => [
'scopes' => array_map('trim', explode(',', env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES', 'snsapi_userinfo'))),
'callback' => env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK', '/examples/oauth_callback.php'),
//'callback'=>'/'
],
],
],
4、在app\Http\Kernel.php 里面添加中间件
'wechat.oauth' => \Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate::class,
5、路由中使用中间件
Route::get('user','HomeController@user')->middleware('wechat.oauth');
6、获取用户信息
$wechat = session('wechat.oauth_user.default');
7、补充:不用看
public function setUserInfo(){
$wechat = session('wechat.oauth_user.default');
$has = \App\Models\User::where('wxopenid', $wechat->id)->first();
if(!$has){
DB::beginTransaction();
$result = DB::table('user')->insertGetId([
'wxname' => $wechat->name,
'wxopenid' => $wechat->id,
'regIp'=> $ip = $_SERVER['REMOTE_ADDR'],
'wxnickname'=>$wechat->nickname,
'wxavatar'=>$wechat->avatar,
'sex'=>$wechat->original['sex'],
'wxcountry'=>$wechat->original['country'],
'wxprovince'=>$wechat->original['province'],
'wxcity'=>$wechat->original['city'],
'email'=>$wechat->email,
'regType'=>'wx',
'loginTime'=>'0',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$bres = DB::table('balance')->insert(['version'=>0,'money'=>0,'user_id'=>$result]);
if($result && $bres){
DB::commit();
$has = \App\Models\User::where('id',$result)->get();
}else{
DB::rollback();
return redirect('/');
}
}else{
$has->timestamps = false;
$has->loginTime = $has->loginTime + 1;
$has->save();
}
return $has;
}