首先需要进行登录验证或token
后台登录
这里是数据表
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\Renting;
use Illuminate\Support\Facades\Cache;
class LoginController extends Controller
{
/**
* Client ID: 1
* Client secret: 5QBqbRm7hPxKVPhqrjR3oSnmd7E7VmpxUXX82SDL
* Password grant client created successfully.
* Client ID: 2
* Client secret: 4PnqKLwlmaZQxhzNsFsxTuFIL5MpMySWoty6Yb5U
*/
//登录方法
public function login(Request $request)
{
try {
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
} catch (\Exception $exception) {
return response()->json(['errorCode' => 10004, 'data' => '', 'msg' => '账号或密码不能为空'], 400);
}
//进行auth
$bool = auth()->guard('api_web')->attempt($request->all());
//登录失败
if (!$bool) {
return response()->json(['errorCode' => 10005, 'data' => '', 'msg' => '账号名或者密码错误'], 400);
}
//登录成功,生成token返回给前台
//第一步获取用户模型
$userModel = auth()->guard('api_web')->user();
//生成了token
$token = $userModel->createToken('api')->accessToken;
//
return response()->json(['errorCode' => 0, 'data' => ['token' => $token, 'expire' => 7200], 'msg' => '登录成功']);
}
//微信登录方法
public function wxLogin(Request $request)
{
//接收参数
$params = $request->all();
//微信小程序登录的url地址
$url = sprintf(config('wx.wxLoginUrl'), config('wx.AppID'), config('wx.AppSecret'), $params['code']);
$client = new Client(['timeout' => 5, 'verify' => false]);
$response = $client->get($url);
$data = (string)$response->getBody();
//转成数据
$data = json_decode($data, true);
//进行查询数据,如果没有进行添加,如果则进行生成token
$renting = Renting::where('openid', $data['openid'])
->first();
// print_r($renting);die;
if (empty($renting)) {
$renting = Renting::create($data);
}
//生成token
$token = $renting->createToken('api')->accessToken;
//存缓存
Cache::set($token, $renting, 7200);
return response()->json(['errorCode' => 0, 'data' => ['token' => $token, 'expire' => 7200,'time'=>time()], 'msg' => '登录成功']);
}
//更新用户信息
public function saveUsers(Request $request)
{
//接收参数
$params = $request->all();
//获取token
$token = explode(' ',$request->header('authorization'))[1];
//进行查看
$userInfo = Cache::get($token);
//更新用户信息完成
$userInfo->update($params);
return response()->json(['errorCode' => 0, 'data' => '', 'msg' => '修改成功']);
}
}
登录接口进行鉴权已经次数限制
小程序登录页
首先在app.js中进行更改
// app.js
App({
onLaunch() {
// logs.unshift(Date.now())
// wx.setStorageSync('logs', logs)
let token = wx.getStorageSync('token')
//token过期时间
let token_expire = wx.getStorageSync('token_expire')
//当前的时间戳
let now_time = Math.round(new Date().getTime() / 1000).toString();
//还剩余多久过期
let expire_time = token_expire - now_time;
if (expire_time <= 0) {
//如果过期,清空缓存
wx.clearStorageSync('token')
wx.clearStorageSync('token_expire')
}
if (!token) {
// 登录
wx.login({
success: res => {
//获取code码
let code = res.code
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: 'http://www.zfw.com/api/v1/wx_login',
method: 'POST',
data: {
code
},
success: res => {
let token = res.data.data.token;
wx.setStorageSync('token', token)
wx.setStorageSync('token_expire', res.data.data.time + res.data.data.expire - 100)
}
})
}
})
}
},
globalData: {
userInfo: null
}
})
然后跳转到列表页
js
// index.js
// 获取应用实例
const app = getApp()
Page({
data: {
goods:[]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getActivityList();
},
getActivityList() {
var token = wx.getStorageSync('token')
wx.request({
url: 'http://www.zfw.com/api/v1/activity_list',
header: {
'Authorization': `Bearer ${token}`
},
success: res => {
let code = res.statusCode.toString()
if (!code.startsWith('2')){
wx.showToast({
title: '异常!',
icon:1
})
}
this.setData({
goods:res.data.data
})
}
})
}
})
wxml
<block wx:for="{{ goods}}" wx:key="unique">
<l-card type="primary" full="{{true}}" image="{{item.goods.goods_image}}" title="{{ item.goods.goods_name}}">
<view>
价格:{{ item.goods.goods_price}}
</view>
<view>
<navigator url="/pages/goods_detail/goods_detail?goods_id={{ item.goods_id }}"> <l-button type="error">参与抢购</l-button></navigator>
</view>
</l-card>
</block>
详情页
js
// pages/goods_detail/goods_detail.js
import {
debounce
} from "../../utils/util"
Page({
/**
* 页面的初始数据
*/
data: {
goods:{},
expire_time:0,
btn_disable:false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (e) {
//商品id
let goods_id = e.goods_id;
this.getGoodsDetail(goods_id)
},
//获取商品详情
getGoodsDetail(goods_id){
var token = wx.getStorageSync('token')
wx.request({
url: 'http://www.zfw.com/api/v1/goods_detail?goods_id='+goods_id,
header: {
'Authorization': `Bearer ${token}`
},
success: res => {
//当前的时间戳
let now_time = Math.round(new Date().getTime() / 1000).toString();
let expire_time = res.data.data.start_time-now_time;
this.setData({
goods:res.data.data,
expire_time
})
if(expire_time > 0){
this.setData({
btn_disable:true
})
}
console.log(this.data.goods)
}
})
},
//立即抢购
buyGoods:debounce(function (e) {
let goods_id = e[0].currentTarget.dataset.goods_id
var token = wx.getStorageSync('token')
wx.request({
url: 'http://www.zfw.com/api/v1/snap_up',
header: {
'Authorization': `Bearer ${token}`
},
method:"POST",
data:{
goods_id
},
success: res => {
let code = res.statusCode.toString()
if (!code.startsWith('2')){
wx.showToast({
title: '异常!',
icon:1
})
}
if(res.data.errorCode == 0){
wx.redirectTo({
url: '/pages/order/order',
})
}else{
wx.showToast({
title: res.data.msg,
})
}
console.log(res.data)
}
})
}),
changeBtn(){
this.setData({
btn_disable:false
})
}
})
wxml
<view>商品秒杀页面</view>
<l-countdown time-type="second" time="{{expire_time}}" bind:linend="changeBtn" />
<l-card type="primary" full="{{true}}" image="{{goods.goods.goods_image}}" title="{{goods.goods.goods_name}}">
<view>
价格:{{goods.goods.goods_price}}
</view>
<view>
<!-- <button disabled="true" bindtap="buyGoods" >抢购</button> -->
<l-button disabled="{{ btn_disable }}" bind:lintap="buyGoods" type="error" data-goods_id="{{ goods.goods.id }}">立即秒杀</l-button>
</view>
</l-card>
下期让我们来实现后台的操作https://blog.csdn.net/m0_56487875/article/details/118603670