IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> 小程序+秒杀+laravel框架编写 -> 正文阅读

[PHP知识库]小程序+秒杀+laravel框架编写

?接口

Route::middleware('auth:api')->prefix('index')->middleware('throttle:1000,1')->group(function (){
    Route::get('ShowIn',[\App\Http\Controllers\show\index::class,'index']);
    Route::get('ShowSel',[\App\Http\Controllers\show\index::class,'sel']);
    Route::get('ShowselShow',[\App\Http\Controllers\show\index::class,'selShow']);
    Route::get('InControllerCreate',[\App\Http\Controllers\show\index::class,'InControllerCreate']);
    Route::get('ShowInSel',[\App\Http\Controllers\show\Showin::class,'sel']);
    Route::get('ShowInDel',[\App\Http\Controllers\show\Showin::class,'del']);
});

小程序获取登录

<view class="container">
  <view class="userinfo">
    <block wx:if="{{!hasUserInfo}}">
      <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
      <button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    </block>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
</view>

?小程序登录页面js

var util = require('../../utils/util');

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    avatarUrl:'',
    nickName:''

  },
  onLoad() {
    var thime=util.formatTime(new Date());
    console.log(thime);
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '勇敢妞妞不怕困难',
      success:(res)=>{
        this.setData({
          avatarUrl:res.userInfo.avatarUrl,
          nickName:res.userInfo.nickName
        })
        wx.login({
          success: (res) =>{
            if (res.code) {
              // 发起网络请求
              wx.request({
                url: 'http://www.ceshi.com/index/ShowIn',
                data: {
                  code: res.code,
                  avatarUrl: this.data.avatarUrl,
                  nickName: this.data.nickName
                },
                success:function(res){
                  console.log(res.data.openid);
                    wx.setStorage({
                      key:"openid",
                      data:res.data.openid
                    })
                    wx.navigateTo({
                      url: '/pages/home/home',
                    })
                },
              })
            } else {
              console.log('登录失败!' + res.errMsg)
            }
          }
        })
      }
    })
},
  navigateBtn:function()
  {
    wx.navigateTo({
      url: 'pages/home/home',
      success: function(res){},
      fail: function() {},
      complete: function() {}
    })
  }
})

?小程序 列表 wxml

<!--pages/home/home.wxml-->
<l-card wx:for="{{name}}" type="primary" 
          full="{{true}}"
          image="{{item.u_img}}"
          title="{{item.u_name}}">
     <view class="content">
      <!-- <l-countdown bind:linend time-type="second" time="{{item.create}}"   format="{%h}:{%m}:{%s}"/> -->
      <l-button type="default" bindtap="bindButtonTap" id="{{item.id}}">默认按钮</l-button>
    </view>
  </l-card>

小程序 列表 js

// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    urname:'',
    res:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getStorage({
      key: 'openid',
      success (res) {
        that.setData({
          res:res.data
        })
      }
    })
    wx.request({
      url: 'http://www.ceshi.com/index/ShowSel',
      data:{
        openid:that.data.res,
        name:that.data.name
      },
      success:function(date){
        console.log(date);
        that.setData({
          name:date.data.date
        })
      }
    })
  },

 bindButtonTap: function(e) {
   var that = this;
   var id =e.currentTarget.id;
   var openid = wx.getStorageSync('openid');
   console.log(id)
   console.log(openid)
   wx.request({
     url: 'http://www.ceshi.com/index/ShowselShow',
     data:{
       id:id,
       name:openid
     },
     success:function(res) {
       wx.navigateTo({
         url: '/pages/show/show?id='+id
       })
     }
   })
  }
})

详情页 wxml

<!--pages/show/show.wxml-->

<l-card wx:for="{{name}}" type="primary" 
          full="{{true}}"
          image="{{item.u_img}}"
          title="{{item.u_name}}">
     <view class="content">
      <l-countdown time-type="second" time="{{expire_time}}" format="{%h}:{%m}:{%s}"  bind:linend="changeBtn" />
      <l-button disabled="{{ btn_disable }}" bind:lintap="buyGoods"   bindtap="bindtapChild"  id="{{true}}">禁用按钮</l-button>
    </view>
  </l-card>

详情页 js

// pages/show/show.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    goods:{},
    expire_time:0,
    id:'',
    btn_disable:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (id) {
    var that = this;
    that.setData({
      id:id.id
    });
    wx.request({
      url: 'http://www.ceshi.com/index/ShowselShow?id='+id.id,
      success:function(res) {
        var update =res.data.name[0].create;
        //当前时间
        var now_time = Math.round(new Date().getTime() / 1000).toString();
        var number = update - now_time;
        that.setData({
          name:res.data.name,
          expire_time:number
        })
      }
    })
  },

  changeBtn(){
    // console.log(1);
    this.setData({
      btn_disable:false
    })
  },

  bindtapChild:function(e){
  var uren = e.currentTarget.id;
  if( uren == 'false' ){  
      wx.showToast({  
          title: '正在禁用',  
          icon: 'error',  
          duration: 2000  
      })  
  }else{
    TimeID:-1,
    clearTimeout(this.TimeID);
          this.TimeID = setTimeout(() => {
          var openid = wx.getStorageSync('openid');
    wx.request({
      url: 'http://www.ceshi.com/index/InControllerCreate',
      data:{
        openid:openid,
        id:this.data.id
      },
      success:function(res) {
        console.log(res.data);
      }
    })
  }, 1000);
  }
  },
  onShareAppMessage: function () {

  }
})

?小程序 获取 缓存值

wx.setStorage({
                key:"openid",
                data:res.data.openid
             })

var openid = wx.getStorageSync('openid');

laravel缓存数据

缓存Cache
\Cache::put('mdopenid',$mdopenid,7200);
查询Cache
 $en= \Cache::get('mdopenid');

laravel 框架 登录?

public function index(Request $request)
    {
        //获取code码
        $code = $request['code'];
        $avatarUrl = $request['avatarUrl'];
        $nickName = $request['nickName'];
        $ser = 'https://api.weixin.qq.com/sns/jscode2session?appid='.config('api.AppID').'&secret='.config('api.AppSecret').'&js_code='.$code.'&grant_type=authorization_code';
        $dae= file_get_contents($ser);
        $json = json_decode($dae,true);
        $openid = $json['openid'];
        $date = rentings::where('openid',$openid)->get()->ToArray();
        if (empty($date)){
            $name['code']=$code;
            $name['avatarUrl']=$avatarUrl;
            $name['nickName']=$nickName;
            rentings::create($name);
        }
        $mdopenid=md5($openid);
        \Cache::put('mdopenid',$mdopenid,7200);
        return ['openid'=>$mdopenid];
    }

?laravel 框架 查询数据

 public function sel(Request $request)
    {
       $name = $request['name'];
        $mdopenid = \Cache::get('mdopenid');
       if ($name == $mdopenid){
           return ['res'=>'未登录'];
       }

       $date = u_commodity::all()->ToArray();
       $datetime = strtotime(date('Y-m-d h:i:s'));
        foreach ($date as $i=>$value)
        {
            $date[$i]['create'] = $value['create']-$datetime;
        }
        return ['date'=>$date];
    }

laravel 框架 详情页查询

    public function selShow(Request $request)
    {
        $id = $request['id'];
        $datetime = strtotime(date('Y-m-d h:i:s'));
        $nameGet = u_commodity::where('id',$id)->get();
        foreach ($nameGet as $value)
        {
            $value['create']= $value['create']-$datetime;
        }
        return  ['name'=>$nameGet];
    }

?减库存

public function InControllerCreate(Request $request)
    {
       $openid = $request['openid'];
       $en= \Cache::get('mdopenid');
       if ($openid != $en){
        return ['res'=>'未登录'];
       }
       //数据查询是否存在
        $data['id'] = $request['id'];
        $user =Order::where('u_id',$data['id'])->where('openid',$openid)->get()->toarray();
        if (!empty($user)){
            return ['code'=>302,'msg'=>'你已抢过了'];
        }

        $goods = u_commodity::find($data['id'])->toarray();
        for(!$i=1; $i <= $goods['number']; $i++){
            Redis::lpush($goods['id'], $i);
        }
        $count = Redis::rpop($goods['id']);
        if ($count != 0 ){
           return $this->SelIn($request['openid'],$request['id']);
        }else{
            return  ['code'=>302,'msg'=>'无库存'];
        }
    }
    public function SelIn($openid,$id)
    {
        $date['openid']=$openid;
        $date['u_id']=$id;
        Order::create($date);
        $this->orderForm($date);
        return  ['code'=>302,'msg'=>'购买成功'];
    }
    //数据库
    public function orderForm($date)
    {
        $id['id'] = $date['u_id'];
        $data = u_commodity::find($id)->ToArray();
        $number['number'] =  $data[0]['number']-1;
        u_commodity::where('id',$id['id'])->update($number);
        return ['code'=>200,'msg'=>'库存已减'];
    }

<?php

namespace App\Http\Controllers\show;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\rentings;
use App\Models\u_commodity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class index extends Controller
{
    public function index(Request $request)
    {
        //获取code码
        $code = $request['code'];
        $avatarUrl = $request['avatarUrl'];
        $nickName = $request['nickName'];
        $ser = 'https://api.weixin.qq.com/sns/jscode2session?appid='.config('api.AppID').'&secret='.config('api.AppSecret').'&js_code='.$code.'&grant_type=authorization_code';
        $dae= file_get_contents($ser);
        $json = json_decode($dae,true);
        $openid = $json['openid'];
        $date = rentings::where('openid',$openid)->get()->ToArray();
        if (empty($date)){
            $name['code']=$code;
            $name['avatarUrl']=$avatarUrl;
            $name['nickName']=$nickName;
            rentings::create($name);
        }
        $mdopenid=md5($openid);
        \Cache::put('mdopenid',$mdopenid,7200);
        return ['openid'=>$mdopenid];
    }
    public function sel(Request $request)
    {
       $name = $request['name'];
        $mdopenid = \Cache::get('mdopenid');
       if ($name == $mdopenid){
           return ['res'=>'未登录'];
       }

       $date = u_commodity::all()->ToArray();
       $datetime = strtotime(date('Y-m-d h:i:s'));
        foreach ($date as $i=>$value)
        {
            $date[$i]['create'] = $value['create']-$datetime;
        }
        return ['date'=>$date];
    }
    public function selShow(Request $request)
    {
        $id = $request['id'];
        $nameGet = u_commodity::where('id',$id)->get();
        return  ['name'=>$nameGet];
    }
    public function InControllerCreate(Request $request)
    {
       $openid = $request['openid'];
       $en= \Cache::get('mdopenid');
       if ($openid != $en){
        return ['res'=>'未登录'];
       }
       //数据查询是否存在
        $data['id'] = $request['id'];
        $user =Order::where('u_id',$data['id'])->where('openid',$openid)->get()->toarray();
        if (!empty($user)){
            return ['code'=>302,'msg'=>'你已抢过了'];
        }

        $goods = u_commodity::find($data['id'])->toarray();
        for(!$i=1; $i <= $goods['number']; $i++){
            Redis::lpush($goods['id'], $i);
        }
        $count = Redis::rpop($goods['id']);
        if ($count != 0 ){
           return $this->SelIn($request['openid'],$request['id']);
        }else{
            return  ['code'=>302,'msg'=>'无库存'];
        }
    }
    public function SelIn($openid,$id)
    {
        $date['openid']=$openid;
        $date['u_id']=$id;
        Order::create($date);
        $this->orderForm($date);
        return  ['code'=>302,'msg'=>'购买成功'];
    }
    //数据库
    public function orderForm($date)
    {
        $id['id'] = $date['u_id'];
        $data = u_commodity::find($id)->ToArray();
        $number['number'] =  $data[0]['number']-1;
        u_commodity::where('id',$id['id'])->update($number);
        return ['code'=>200,'msg'=>'库存已减'];
    }
}

  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章      下一篇文章      查看所有文章
加:2021-07-10 14:19:19  更:2021-07-10 14:20:59 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 1:49:14-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码