当前位置:网站首页>Silent authorization login and registration of wechat applet
Silent authorization login and registration of wechat applet
2022-07-03 04:49:00 【Xiafei997】
Automatic loading :
onLoad: function (options) {
wx.login({
success (res) {
// console.log(res.code)
if (res.code) {
// Initiate network request
wx.request({
url: 'http://www.day.com/index.php/wxLogin',
method:'GET',
data: {
// nickName:nickName,
code: res.code
},
success(res){
console.log(res)
// // cache openid
wx.setStorage({
key:"openid",
data:res.data.openid
})
// cache token
wx.setStorageSync('token', res.data.token)
}
})
} else {
console.log(' Login failed !' + res.errMsg)
}
}
})
},
backstage :
// Wechat Authorization
public function wxLogin(Request $request)
{
// obtain code
$code = $request->get('code');
// Get a nickname
$nickName ="aa";
// obtain appId
$appId = "wxa2469ff6402360ff";
// obtain appSecret
$appSecret = "47732169fb165797f0303f1f781de142";
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
$headerArray = array("Content-type:application/json;", "Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output, true);
$session_key = $output['session_key'];
$openid = $output['openid'];
// Query exists openid
$postdata = \app\model\Index::selectData($openid);
$data = [
'nickname' => $nickName,
"openid" => $openid,
"session_key" => $session_key
];
if (!$postdata) {
\app\model\Index::addData($data);
} else {
\app\model\Index::changeData($openid, $data);
}
$key = "example_key";
// $payload = array(
// 'id' => $postdata->id
// );
// $token = JWT::encode($payload, $key, 'HS256');
$id=$postdata->id;
// dd($id);
// Issued by token
$token=\app\jwt\Jwt::createJwt($id);
return json([
'openid' => $data['openid'],
'token' => $token,
'id'=>$id
]);
}// Query data
public static function selectData($openid)
{
return self::where('openid', $openid)->find();
}
// Add data
public static function addData($data)
{
return self::create($data);
}
// Modifying data
public static function changeData($openid, $data)
{
return self::where("openid", $openid)->save($data);
}download jwt: composer require firebase/php-jwt
jwt file :
<?php
namespace app\jwt;
use Firebase\JWT\Key;
use think\Exception;
class Jwt
{
// Generate token
public static function createJwt($userId = 'zq')
{
$key = md5('[email protected]!'); //jwt Issuing key for , verification token It needs to be used
$time = time(); // The issuance of time
$expire = $time + 14400; // Expiration time
$token = array(
"user_id" => $userId,
"iss" => "http://www.najingquan.com/",// Issuing organization
"aud" => "zhangqi", // Issued by
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
$jwt = \Firebase\JWT\JWT::encode($token, $key,'HS256');
return $jwt;
}
// check jwt jurisdiction API
public static function verifyJwt($jwt = '')
{
$key = md5('[email protected]!');
try {
$jwtAuth = json_encode(\Firebase\JWT\JWT::decode($jwt, new Key($key,'HS256')));
$authInfo = json_decode($jwtAuth, true);
$msg = [];
if (!empty($authInfo['user_id'])) {
$msg = [
'status' => 1001,
'msg' => 'Token Verification passed '
];
return $authInfo['user_id'];
} else {
throw new Exception('Token Verification failed , The user doesn't exist ');
// $msg = [
// 'status' => 1002,
// 'msg' => 'Token Verification failed , The user doesn't exist '
// ];
}
} catch (\Firebase\JWT\ExpiredException $e) {
throw new Exception('Token Be overdue ');
// exit;
} catch (\Exception $e) {
throw new Exception('Token Invalid ');
}
}
}middleware :
public function handle($request, \Closure $next)
{
$token=$_SERVER["HTTP_TOKEN"];
// dd($token);
try {
$user_id=Jwt::verifyJwt($token);
$request->user_id=$user_id;
}catch (Exception $exception){
return json(['token Acquisition failure ']);
}
return $next($request);
}
}
边栏推荐
- Market status and development prospect prediction of the global fire alarm sensor industry in 2022
- JDBC database operation
- Market status and development prospect forecast of global button dropper industry in 2022
- Employee attendance management system based on SSM
- 2022 registration examination for safety production management personnel of hazardous chemical production units and examination skills for safety production management personnel of hazardous chemical
- Leetcode simple question: check whether two string arrays are equal
- Two drawing interfaces - 1 Matlab style interface
- Sdl2 + OpenGL glsl practice (Continued)
- 【XSS绕过-防护策略】理解防护策略,更好的绕过
- Youdao cloud notes
猜你喜欢

Use Sqlalchemy module to obtain the table name and field name of the existing table in the database

MediaTek 2023 IC written examination approved in advance (topic)
![[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)](/img/36/53886b9d3b98f744be2b6aa6b5d3eb.jpg)
[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)

JVM原理简介

Leetcode simple question: the key with the longest key duration

Shuttle + Alluxio 加速内存Shuffle起飞

Employee attendance management system based on SSM

MC Layer Target

联发科技2023届提前批IC笔试(题目)

The programmer went to bed at 12 o'clock in the middle of the night, and the leader angrily scolded: go to bed so early, you are very good at keeping fit
随机推荐
I stepped on a foundation pit today
AWS VPC
带有注意力RPN和多关系检测器的小样本目标检测网络(提供源码和数据及下载)...
文献阅读_基于多模态数据语义融合的旅游在线评论有用性识别研究(中文文献)
Youdao cloud notes
Market status and development prospect prediction of global fermented plant protein industry in 2022
Auman Galaxy new year of the tiger appreciation meeting was held in Beijing - won the double certification of "intelligent safety" and "efficient performance" of China Automotive Research Institute
Market status and development prospect prediction of global fermentation acid industry in 2022
Why should programmers learn microservice architecture if they want to enter a large factory?
2022 a special equipment related management (elevator) analysis and a special equipment related management (elevator) simulation test
Learning practice: comprehensive application of cycle and branch structure (I)
联发科技2023届提前批IC笔试(题目)
2.14 summary
Golang -- realize file transfer
Thesis reading_ Chinese NLP_ ELECTRA
Leetcode simple question: check whether the array is sorted and rotated
[SQL injection] joint query (the simplest injection method)
MPM model and ab pressure test
First + only! Alibaba cloud's real-time computing version of Flink passed the stability test of big data products of the Institute of ICT
[set theory] relational representation (relational matrix | examples of relational matrix | properties of relational matrix | operations of relational matrix | relational graph | examples of relationa