这段时间在做电商的小程序,前期在登录注册上花了不少功夫,今天就给大家分享下。
这里用的后台框架是 laravel8.0,
首先需要在后台文件新建几个文件:
现在控制器文件夹创建一个api文件夹(为了代码的规范性)
在api文件夹中创建控制器:
LoginController
ProductsController
控制器互相关联,不可缺少任何一个
首先编辑ProductsController
新建shopGoods方法
public function shopGoods(Request $request){
}
注意别忘了引入方法
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
在此方法内写入
$openid = $request->get('openid');
$token = $request->get('token');
//获取openid和token
$user = User::where('token',$token)->first();
if (!$user)
return response()->json(['status'=>1001,'msg'=>'请先登录!'],401);
$cates = (Category::limit(8)->get(['id','name','icon_url']))->toArray();
$goods = Product::limit(5)->get(['id','category_id','title','price','image'])->toArray();
$data = [
'cates'=> $cates,
'goods'=> $goods
];
return response()->json(['status'=>200,'data'=>$data],200);
开始写LoginController方法
注意引入方法
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\User;
首先编写login方法用来判断登录等方法
public function login(Request $request)
{
}
在login方法内编写
try{
$this->validate($request,[
'name'=>'required',
'password'=>'required'
]);
}catch (\Exception $exception){
return response()->json(['status'=>1000,'msg'=>'账号或密码不能为空'],400);
}
$bool = auth()->guard('web')->attempt($request->all());
if ($bool){
$userModel = auth()->guard('web')->user();
// dd($userModel);
$token = "123456abcedf";
$data = [
'expire'=>7200,
'token'=>$token
];
// dd($bool);
$userModel->update(['token'=>$token]);
return response()->json($data);
}else{
return response()->json(['status'=>1001,'msg'=>'账号或密码不正确'],401);
}
之后开始写wxlogin方法
注意需要自己小程序的appid,在这里用我提供的也可以(如果出错,可以先替换成自己的appid尝试)
public function wxlogin(Request $request)
{
}
方法内填写
$appid = 'wx61b7c33c30dd4a02';
$secret = '3ebf463e0a8077cade11e8f4b22bef65';
$code = $request->get('code');
$token = $request->get("token");
$user = User::where('token',$token)->first();
if (!$user){
return response()->json(['status'=>1001,'msg'=>'请先登录!'],401);
}
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
$url = sprintf($url,$appid,$secret,$code);
$client = new Client(['timeout'=>5,'verify'=>false]);
$response = $client->get($url);
$xcxRet = (string)$response->getBody();
$temp = json_decode($xcxRet,true);
try{
User::where('token',$token)->update(['openid'=>$temp['openid']]);
}catch (\Exception $exception){
return [];
}
return $xcxRet;
之后记得编写路由
一定要在routes目录下的api.php编写,不要在web.php!!
Route::post('login','Api\LoginController@login');
Route::post('tg/wxlogin','Api\LoginController@wxlogin');
Route::post('tg/shopgoods','Api\ProductsController@shopGoods');
之后就是开始编写小程序页面
一定要记得编写tabar
"tabBar": {
"color": "#999",
"selectedColor": "#ff2d4a",
"backgroundColor": "#fff",
"position": "bottom",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/shop/shop",
"text": "商城首页",
"iconPath": "/icon/[email protected]",
"selectedIconPath": "/icon/[email protected]"
},
{
"pagePath": "pages/index/index",
"text": "条件页",
"iconPath": "/icon/[email protected]",
"selectedIconPath": "/icon/[email protected]"
}
]
},
这里讲解用两个页面测试
"pages/login/login",
"pages/shop/shop"
我们首先编写login页面
login.wxml
<view class="Login_wrap">
<view class="login_input">
<form bindsubmit="formSubmit" class="form_wrap">
<input class="input" placeholder-class="placeholder-class" type="text" name="name" placeholder="用户名" />
<input class="input" placeholder-class="placeholder-class" type="password" name="pwd" password="true" placeholder="密码" />
<button class="button" formType="submit">登录</button>
</form>
</view>
</view>
编写表单页面
之后开始写js方法
这里也需要在最上方引入方法然后实例化
import utils from '../../utils/util.js'
import cache from '../../utils/Cache.js'
import Http from '../../utils/Http.js'
//上面引入方法
const http = new Http;
//实例化
在data中初始化数据
modal: {
hidden: true,
msg: ''
},
toast: {
hidden:true,
msg: ''
}
开始编写方法:
验证并写入数据
formSubmit : function(e){
let name = e.detail.value.name,
pwd = e.detail.value.pwd;
// console.log(email,'--',pwd); return;
if(!name){
this.setData({
"modal.hidden" : false,
"modal.msg" : "请填写手机号"
});
return ;
}else if(!pwd){
this.setData({
"modal.hidden" : false,
"modal.msg" : "请填写密码"
});
return ;
}
// pwd = utils.md5(pwd);
this.apilogin(name,pwd);
},
数据是否存在:
modalChange : function(e){
this.setData({
"modal.hidden" : true,
"modal.msg" : ""
})
},
传入并跳转
apilogin(name,password){
// 接口登录
if (!cache.has('token')) {
http.httpReq({
url: 'http://www.yzanshop.com/index.php/api/login',
method: "POST",
data: {
'name': name, 'password': password }
}).then(ret=>{
cache.set('token',ret.data.token);
if (!cache.has('openid')) {
// 登录
this.wxlogin(ret.data.token);
}else{
wx.switchTab({
url: '../shop/shop',
});
}
})
}else{
wx.switchTab({
url: '../shop/shop',
});
}
},
判断openid
wxlogin(token){
wx.login({
timeout: 2000,
success: ({
code })=>{
// 发起网络请求
http.httpReq({
url: 'http://www.yzanshop.com/api/tg/wxlogin',
method: 'POST',
data: {
code,token }
}).then(ret=>{
cache.forever('openid',ret.data.openid);
if (ret.data.openid) {
let app=getApp();
app.globalData.openid = ret.data.openid;
app.globalData.token = token;
wx.switchTab({
url: '../shop/shop',
})
}
})
}
})
}
之后开始编写shop页面
首先写shop.js
记得引入方法和实例化
import utils from '../../utils/util.js'
import cache from '../../utils/Cache.js'
import Http from '../../utils/Http.js'
const http = new Http;
初始化data数据:
data: {
openid: '',
token: '',
goods: [],
cates: []
},
编写 生命周期函数–监听页面加载:
onLoad: function (options) {
let app = getApp();
this.openid = app.globalData.openid ? app.globalData.openid : cache.get('openid');
this.token = app.globalData.token ? app.globalData.token: cache.get('token');
http.httpReq({
url:'http://www.yzanshop.com/index.php/api/tg/shopgoods',
data: {
token: this.token,openid: this.openid },
method: "POST"
}).then(({
status,data})=>{
let {
cates, goods } = data.data
console.log(cates);
console.log(goods);
this.setData({
cates,
goods
})
});
},
开始编写shop.wxml
先写个轮播图
<swiper autoplay="{
{ true }}" interval="{
{ 1500 }}" circular="{
{ true }}"
indicator-dots="{
{ true }}">
<block wx:for="{
{ [1,2,3,4] }}" wx:key="swiper">
<swiper-item>
<image src="/imgs/img{
{ item }}.jpeg" mode="aspectFill"></image>
</swiper-item>
</block>
</swiper>
分类展示
<view class="cate">
<view class="icon">
<block wx:for="{
{ cates }}" wx:key="cates">
<view class="icon-item">
<image src="/imgs/banner{
{ index+1 }}.png"></image>
<view>{
{
item.name }}</view>
</view>
</block>
</view>
</view>
页面展示:
<view class="list">
<view class="goodslist">
<block wx:for="{
{ goods }}" wx:key="goods">
<view class="goods-item">
<!-- <image src="/imgs/goods/{
{ index+1 }}mi.jpg"></image> -->
<image src="{
{ item.image }}"></image>
<view>{
{
item.title }}</view>
</view>
</block>
</view>
</view>
wxss样式可以参考我的试一下
/* pages/shop/shop.wxss */
@import '/style/font.wxss';
page{
font-size: 16px;
}
view{
/* border: 1px solid red; */
}
image{
width: 750rpx;
height: 340rpx;
}
.search{
display: flex;
justify-content: space-between;
align-items: center;
height: 80rpx;
line-height: 80rpx;
/* background-color: #e43130; */
background-color: #ffffff;
color: #f00;
}
.search view:nth-of-type(1)
{
margin-left: 20rpx;
}
.search view:nth-of-type(3)
{
margin-right: 20rpx;
}
.search view:nth-of-type(2)
{
width: 550rpx;
height: 60rpx;
line-height: 60rpx;
}
.cate{
margin-top: 2px;
}
.icon{
width: 750rpx;
height: 340rpx;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.icon-item{
width:180rpx;
height:150rpx;
font-size: 12px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
.icon-item image{
width:80rpx;
height: 80rpx;
}
.list{
margin-top: 2px;
}
.goodslist{
width: 750rpx;
height: 340rpx;
display: flex;
flex-direction: row;
justify-content: space-between;
flex-wrap: wrap;
}
.goods-item{
width:350rpx;
height: 340rpx;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
.goods-item image{
width: 350rpx;
height: 320rpx;
}
然后一整套登录注册和跳转就做完了!
有什么不懂的可以留言,我看到后会回复!