微信小程序 用户登录 服务器端(TP5.1)实现
先来看官方提供的流程图:

客户端:
小程序客户端通过 wx.login() 获取登录code , 然后将code当做参数传递到服务器、
getToken(){
var that = this;
wx.login({
success: function (res) {
wx.request({
url: 'http://wx.shop.com/api/v1/token', //服务器获取token的api
method:'POST',
data: {
code : res.code
},
success: function (res) {
console.log(res)
}
})
}
})
}
服务器端(ThinkPHP5.1):
1. 根据客户端传递的 code , 请求微信提供 api 换取该用户的 openid 和 session_key ,同一个用户在同一个小程序中的 openid 是不变的
<?php
namespace app\common\service;
use app\common\model\User;
/**
* UserToken类用作颁发微信令牌,继承与Token
*/
class UserToken extends Token {
protected $code;
protected $Appid;
protected $AppSecret;
protected $LoginUrl; public function __construct($code) {
$this->code = $code; //从服务器换取 openid 需要传递三个参数
// Appid、Appsecret、Code
$this->Appid = config('wx.app_id');
$this->AppSecret = config('wx.app_secret'); //sprintf的作用是将字符串中占位符用特定值按顺序替换
$this->LoginUrl = sprintf(config('wx.login_url'), $this->Appid, $this->AppSecret, $this->code);
}
/**
* 根据用户传递 code 去微信服务器换取 openid
*/
public function get() {
$result = curl_get($this->LoginUrl);
$wxResult = json_decode($result, true);
if (empty($wxResult)) {
throw new Exception("获取session_key和open_id失败,微信内部错误");
}
//验证获取令牌是否成功
if (array_key_exists('errcode', $wxResult)) {
throw new \app\common\exception\BaseException([
'errorCode' => $wxResult['errcode'],
'msg' => $wxResult['errmsg'],
]);
} else {
return $this->grantToken($wxResult['openid']);
}
}
/**
* 颁发令牌 并将用户信息序列化成json,已token为键保存在本地缓存
* 作用是 当用户不存在时创建用户 存在时返回用户 id
*/
private function grantToken($openid) {
//查找User表,查看该openid对应用户是否存在,如是则返回uid,否则生成新用户,返回uid
$user = User::where('openid', $openid)->find();
if (!$user) {
$uid = User::create([
'openid' => $openid,
]);
} else {
$uid = $user->id;
}
//存入缓存 key:生成返回客户端的令牌 value:openid + uid
$key = $this->generateToken();
$cache_value['openid'] = $openid;
$cache_value['uid'] = $uid;
$expire = config('token.expire');
if (!cache($key, $cache_value, $expire)) {
throw new Exception("缓存客户令牌时出现错误");
} else {
return $key;
}
}
}
使用前需要先定位配置文件
<?php return [
// +---------------------------------
// 微信相关配置
// +--------------------------------- // 小程序app_id
'app_id' => 'wx0a1d95f443204af2',
// 小程序app_secret
'app_secret' => 'a29462308699ae469d5fb6cc54a9a95a', // 微信使用code换取用户openid及session_key的url地址
'login_url' => "https://api.weixin.qq.com/sns/jscode2session?" .
"appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", // 微信获取access_token的url地址
'access_token_url' => "https://api.weixin.qq.com/cgi-bin/token?" .
"grant_type=client_credential&appid=%s&secret=%s", //支付状态
'unpaid' => 1,
'paid' => 2,
'shipped' => 3,
];
基类Token
<?php
namespace app\common\service;
use think\Facade\Request; // 这里将token的相关操作放在service层
// 定义了一个Token基类,基类中存放生成 token、根据token从缓存中获取用户数据操作 class Token {
/**
* 生成随机字符串 作为 token
*/
public function generateToken() {
$randChar = getRandChar(32);
$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
return md5($randChar . $timestamp);
}
/**
* 根据用户携带的 token ,从缓存中读取用户信息
*/
public static function getCurrentIdentity() {
$token = Request::header('token');
if (!$token) {
throw new \app\common\exception\BaseException(['msg' => '请先登录']);
}
$identity = cache($token);
if ($identity) {
return $identity;
} else {
throw new \app\common\exception\BaseException(['msg' => '身份已过期,请重新登录']);
}
}
/**
* 获得保存在缓存指定键的值
*/
public static function getCurrentTokenVar($var) {
$indentity = self::getCurrentIdentity();
if (!$indentity[$var]) {
throw new Exception(['msg' => '尝试获取的Token变量并不存在']);
} else {
return $indentity[$var];
}
}
}
控制器中使用
class Token extends Controller {
public function getToken() {
$code = $this->request->param('code');
(new TokenValidate())->getToken($code);
$ut = new UserToken($code);
return json([
'token' => $ut->get(),
]);
}
}
微信支付等操作都依赖于 openid
微信小程序 用户登录 服务器端(TP5.1)实现的更多相关文章
- 微信小程序 --- 用户登录
整体逻辑:点击用户中心,如果如果整个页面没有
- php(ThinkPHP)实现微信小程序的登录过程
源码也在我的github中给出 https://github.com/wulongtao/think-wxminihelper 下面结合thinkPHP框架来实现以下微信小程序的登录流程,这些流程是结 ...
- 使用Shiro+JWT完成的微信小程序的登录(含讲解)
使用Shiro+JWT完成的微信小程序的登录 源码地址https://github.com/Jirath-Liu/shiro-jwt-wx 微信小程序用户登陆,完整流程可参考下面官方地址,本例中是按此 ...
- 完整微信小程序授权登录页面教程
完整微信小程序授权登录页面教程 1.前言 微信官方对getUserInfo接口做了修改,授权窗口无法直接弹出,而取而代之是需要创建一个button,将其open-type属性绑定getUseInfo方 ...
- 微信小程序维护登录态与获取用户信息
前言. 微信小程序的运行环境不是在浏览器下运行的.所以不能以cookie来维护登录态.下面我就来说说我根据官方给出的方法来写出的维护登录态的方法吧. 一.登录态维护 官方的文档地址:https://m ...
- 微信小程序之登录连接django,以及用户的信息授权认证
小结: 1 如何自定义组件 - 组件和页面一样,也是由四个文件组成,所以我们自定义组件的时候,模拟pages文件夹,把所有的所有的组件都放在一个文件夹中,每个组件又由一个文件夹包裹,方便管理,在对应目 ...
- 使用uni-app开发微信小程序之登录模块
从微信小程序官方发布的公告中我们可获知:小程序体验版.开发版调用 wx.getUserInfo 接口,将无法弹出授权询问框,默认调用失败,需使用 <button open-type=" ...
- Django基于JWT实现微信小程序的登录和鉴权
什么是JWT? JWT,全称Json Web Token,用于作为JSON对象在各方之间安全地传输信息.该信息可以被验证和信任,因为它是数字签名的. 与Session的区别 一.Session是在服务 ...
- 微信小程序之登录态维护(十一)
[未经作者本人同意,请勿以任何形式转载] >什么是登录态? 所谓登录态,就是程序在运行时,能够识别当前用户,能够证明自己的唯一性且合法. 我们知道,WEB服务器通过浏览器携带的cookie获取s ...
随机推荐
- springcloud Eureka学习笔记
最近在学习springcloud,抽空记录下学习笔记;主要记录Eureka的实现过程和高可用性的实现 Eureka是一个服务治理框架,它提供了Eureka Server和Eureka Client两个 ...
- springboot区分开发、测试、生产多环境的应用配置(二)
转:https://www.jb51.net/article/139119.htm springboot区分开发.测试.生产多环境的应用配置(二) 这篇文章主要给大家介绍了关于maven profil ...
- Element分页组件prev-text和next-text属性无效?
前情提要 /(ㄒoㄒ)/~~ 作为刚刚接触 Element 组件的人来说,看文档是第一步,但是当我想要修改分页组件里面的按钮时却遇到了问题. 文档中写到是需要给 prev-text 和 next-te ...
- Keras学习笔记(完结)
使用Keras中文文档学习 基本概念 Keras的核心数据结构是模型,也就是一种组织网络层的方式,最主要的是序贯模型(Sequential).创建好一个模型后就可以用add()向里面添加层.模型搭建完 ...
- flask中自定义过滤器
第一种方法: 1,第一步:自定义过滤器函数 # 自定义一个函数,将list里面的数据进行排序 def list_sort(list) return list.sort() 2.第二步:注册过滤器 第一 ...
- Js强制转换
Js强制转换 ParseInt(a,b):整型 只能放字符串,b为基数.声明前面的数是几进制.因为只能放字符串,所以无论放什么都转换为字符串: 如果String以0x开头则为16进制的整数: ‘036 ...
- 如何将项目连接数据库(连接mysql)
首先需要在项目中加入这一串代码: //加载驱动类 连接数据库有多种方式 比如:jdbc 桥接 Connection con=null; try { Class.forName("com.my ...
- Redis中存入存储的编码方式不一致解决问题
在利用redis缓存的时候,存入的数据与取出的数据编码方式不一致解决办法. from redis import StrictRedis #ecoding = 'utf-8',默认解码方式为bytes, ...
- 使用sshpass方式实现ssh自动登录
1:sshpass下载地址(用yum安装不了) https://sourceforge.net/projects/sshpass/files/ or wget http://sourcef ...
- css 样式控制文本过长实现省略号
css 样式控制文本过长实现省略号 .topicTitle{ text-overflow: ellipsis; max-width: 75%; overflow: hidden; white-spac ...