登陆流程
1、【小程序】调用wx.login() 获取 code给服务器
2、【服务器】用code换 openid 和session_key,随机生成trd_session,保存【trd_session=>"openid,session
_key"】到cache,返回trd_session
3、【小程序】把trd_session保存到storage
小程序端
// 登录
wx.login({ success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: '【url】',
data:{code:res.code},
success: res => { wx.setStorage({ key: "trd_session", data: res.data }) } }) } })
服务器端
composer require guzzlehttp/guzzle
composer require predis/predis
composer require illuminate/redis
去除
$app->withFacades();$app->withEloquent();
注册
$app->register(Illuminate\Redis\RedisServiceProvider::class);
.env中
CACHE_DRIVER=redis
use Illuminate\Http\Request;
$router->get('/code', function (Request $request) {
// 获取open_id session_key
$appid = env('APP_ID');
$secret = env('APP_SECRET');
$js_code = $request->input('code');
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";
$client = new \GuzzleHttp\Client();
$response = $client->get($url);
$res = json_decode($response->getBody()); /
/生成trd_session 保存到cache
$expires_in = $res->expires_in;
$session_key = $res->session_key;
$openid = $res->openid;
$trd_session = md5($session_key);
Cache::put($trd_session, "$openid,$session_key" , $expires_in);
return $trd_session;
});