在同一个文件夹下面
封装一个 http.js (功能) 和 config.js(配置) 文件
http.js?
import config from "../utils/config.js" //引用config
class Http{
request({url , data = {} , method = "GET", auth = true}){
let header = {}
let token = wx.getStorageSync(config.TOKEN_NAME)
// 判断
if(auth){
if(!token){
let that = this
return this.login().then(res=>{
if(res.code==200){
wx.setStorageSync(config.TOKEN_NAME, res.data.token)
wx.setStorageSync(config.TOKEN_EXPIRE, res.data.expire)
return that.wxlogin().then(ret=>{
if(ret.code==200){
wx.setStorageSync(config.OPENID_NAME, ret.data.openid);
data.openid = ret.data.openid
return that.request({
url,data,method
})
}
})
}
})
}
}
header.Authorization = 'Bearer ' + token
return new Promise(function(resolve,reject){
wx.request({
url: `${config.DOMATN}/api/${url}`, //这里 config.DOMATN是域名 ,后面接上 自定义路由
data:data,
header:header,
method:method,
success:res=>{
resolve(res.data)
},fail:ret=>{
reject(ret.data)
//提示 并记录日志
wx.showToast({
title: '系统错误,请稍后再试',
})
}
})
})
}
//登录 获取token
login(){
return this.request({
url:"login",
auth:false,
data:{
username:'admin',
password:'123456',
},
method:'post',
})
}
//用 code 交换 openid
wxlogin(){
let that = this
return new Promise(function(resolve,reject){
wx.login({
timeout: 2000,
success:res=>{
that.request({
url:'v1/wxlogin',
method:'post',
data:{code:res.code}
}).then(res=>{
resolve(res);
})
}
})
})
}
}
export {
Http
}
2.config.js
export default {
DOMATN : "域名地址",
TOKEN_NAME : "token", //保存token 名称
TOKEN_EXPIRE : "expire", //过期时间
OPENID_NAME : "openid", // openid
}
3. 如何在页面引入 (在页面的js 文件中)
import {Http} from "../../utils/Http.js";
let http = new Http;
4.这里登录生成jwt 参考
laravel8 利用passport 登录和 jwt (生成token)_guanj0623的博客-CSDN博客
5.使用code 换 openid? (自己使用的是PHP方法)
public function wxlogin(Request $request)
{
//微信开发助手提供的
$appid = "wx6f45f6ff1ca6c025";
$secret = "5ebd7560baa543f1dca5188fb9630a6c";
//接收传来的code
$code = $request->post('code');
//请求地址 换取openid 和 session_key
$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
$userInfo = json_decode(file_get_contents($url),true);
//根据获取的openid 查询数据 存在的话就更新session_key
$model = Renting::where('openid',$userInfo['openid'])->first();
if ($model){
$model->session_key = $userInfo['session_key'];
$model->save();
}else{
//不存在 将数据入库
Renting::create($userInfo);
}
return ['code'=>200,'msg'=>'success','data'=>$userInfo];
}
|