封装wx.request方法为异步
/**
* 封装request
*/
export default function (options) {
return new Promise((resolve, reject)=> {
wx.request({
url: options.url,
method: options.method || 'get',
data: options.data || {},
header: options.header,
success: resolve,
fail: reject
})
})
}
调用示例
页面传参
接收
组件传参
接收
子传父
父组件接收
弹窗组件
wxml:
<!--components/popup/popup.wxml-->
<view class="wx-popup" hidden="{{flag}}">
<view class='popup-container'>
<view class="wx-popup-titlel" >请选择类型</view>
<view class="back" bindtap="showPopup">返回</view>
<view class="wx-popup-title" bindtap="upload_photo">上传图片</view>
<view class="wx-popup-title" bindtap="upload_file">上传微信文件</view>
</view>
</view>
wxss:
/* components/popup/popup.wxss */
.wx-popup {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, .5);
}
.popup-container {
position: absolute;
left: 50%;
top: 50%;
width: 80%;
max-width: 600rpx;
border: 2rpx solid #ccc;
border-radius: 10rpx;
box-sizing: bordre-box;
transform: translate(-50%, -50%);
overflow: hidden;
background: #fff;
}
.wx-popup-title {
width: 100%;
padding: 20rpx;
text-align: center;
font-size: 40rpx;
color: gray;
border-bottom: 2rpx solid rgb(53, 124, 231);
}
.wx-popup-titlel {
width: 100%;
padding: 20rpx;
text-align: center;
font-size: 40rpx;
color: #5637d2;
border-bottom: 2rpx solid rgb(164, 30, 218);
}
.wx-popup-con {
margin: 60rpx 10rpx;
text-align: center;
}
.wx-popup-btn {
display: flex;
justify-content: space-around;
margin-bottom: 40rpx;
}
.wx-popup-btn text {
display: flex;
align-items: center;
justify-content: center;
width: 30%;
height: 88rpx;
border: 2rpx solid #ccc;
border-radius: 88rpx;
}
.back{
color: rgb(241, 24, 16);
position: fixed;
right: 0;
top: 0;
font-size: 36rpx;
}
js:
// components/popup/popup.js
import {upload} from "../../service/file.js"
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
/**
* 组件的属性列表
*/
properties: {
flag:{
type: Boolean,
value: ''
},
team:{
type: Object,
value: ''
}
},
/**
* 组件的初始数据
*/
data: {
flag: true,
team: ''
},
/**
* 组件的方法列表
*/
methods: {
//隐藏弹框
hidePopup: function () {
this.setData({
flag: !this.data.flag
})
},
//展示弹框
showPopup () {
this.setData({
flag: !this.data.flag
})
this.triggerEvent("showbudge",this.data.flag)
},
// 上传图片
// upload_photo(){
// const that = this
// wx.chooseImage({
// count: 9,
// success(res){
// const images = res.tempFilePaths
// wx.showLoading({
// title: '上传中!',
// })
// for (let index = 0; index < images.length; index++) {
// upload(images[index],that.data.team.teamId).then(res=>{
// if(JSON.parse(res.data).msg == '1'){
// wx.hideLoading();
// wx.showToast({
// title: '上传成功!',
// icon: 'none',
// duration: 2000
// },2000)
// setTimeout(function () {
// //要延时执行的代码
// that.showPopup()
// }, 1000) //延迟时间 这里是1秒
// }
// })
// }
// }
// })
// },
// upload_file(){
// const that = this
// wx.chooseMessageFile({
// count: 1,
// type: 'all',
// success(res){
// // console.log(res)
// wx.showLoading({
// title: '上传中!',
// })
// const file = res.tempFiles[0].path
// upload(file,that.data.team.teamId).then(res=>{
// if(JSON.parse(res.data).msg == '1'){
// wx.hideLoading();
// wx.showToast({
// title: '上传成功!',
// icon: 'none',
// duration: 2000
// },2000)
// setTimeout(function () {
// //要延时执行的代码
// that.showPopup()
// }) //延迟时间 这里是1秒
// }
// })
// }
// })
// },
}
})
遍历
登录获取openid
login(){
wx.getUserProfile({
desc: 'desc',
success:(res)=>{
wx.showLoading({
title: '登录中!',
})
wx.login({
success: (data) => {
// 调用后台接口
login(res.encryptedData,res.iv,data.code).then(res => {
// 以下自己业务逻辑代码
if (res.data.msg == '1') {
const userInfo_ = res.data.data;
// console.log(userInfo_)
const app = getApp()
app.globalData.userInfo = userInfo_
getToken(userInfo_).then(tok => {
wx.hideLoading();
wx.showToast({
title: '登录成功!',
icon: 'none',
duration: 2000
},2000)
// 授权成功
if(tok.data.data.accessToken){
app.globalData.token = tok.data.data.accessToken;
this.setData({
token: tok.data.data.accessToken
})
}else{
console.log('授权失败!')
}
})
} else {
console.log('解密失败')
}
})
}
})
}
})
},
封装的login
export function login(encryptedData, iv, code){
return request({
url: baseURL+'/login',//自己的服务接口地址
method: 'post',
data: {
encryptedData: encryptedData,
iv: iv,
code: code,
}
})
}
后台获取openid
package com.example.outh2_asscess.Controller;
import com.example.outh2_asscess.Service.UserService;
import com.example.outh2_asscess.common.bean.VResponse;
import com.example.outh2_asscess.model.User;
import com.example.outh2_asscess.model.Weichat;
import com.example.outh2_asscess.untils.AesCbcUtil;
import com.example.outh2_asscess.untils.HttpRequest;
import com.example.outh2_asscess.untils.Radom;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@CrossOrigin
public class WeiChatLoginController {
private static final String APPID = "自己的id";
private static final String SECRET = "自己的secret";
@Autowired
private UserService userService;
@ResponseBody
@PostMapping("/login")
public VResponse<User> login(@RequestBody Weichat weichat) throws JSONException, HttpRequestMethodNotSupportedException {
// 登录凭证不能为空
if (weichat.getCode() == null || weichat.getCode().length() == 0) {
return VResponse.error(0,"code不能为空!");
}
System.out.println(weichat);
// 小程序唯一标识 (在微信小程序管理后台获取)
String wxspAppid = APPID;
// 小程序的 app secret (在微信小程序管理后台获取)
String wxspSecret = SECRET;
// 授权(必填)
String grant_type = "authorization_code";
// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + weichat.getCode() + "&grant_type="
+ grant_type;
// 发送请求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
// System.out.println(sr);
// 解析相应内容(转换成json对象)
JSONObject json = new JSONObject(sr);
// 获取会话密钥(session_key)
String session_key = json.get("session_key").toString();
// 用户的唯一标识(openid)
String openid = (String) json.get("openid");
// 以下为自己的业务逻辑
// 查找表中用户是否存在
// User user = userService.findUserByopenid(openid);
// if (user != null){
// return VResponse.success("1",user);
// }
// User userinfo = new User();
// Radom radom = new Radom();
// 2、对encryptedData加密数据进行AES解密
// try {
// String result = AesCbcUtil.decrypt(weichat.getEncryptedData(), session_key, // weichat.getIv(), "UTF-8");
// if (null != result && result.length() > 0) {
// JSONObject userInfoJSON = new JSONObject(result);
// userinfo.setUserName(userInfoJSON.get("nickName").toString());
// userinfo.setUserOpenid(openid);
// userinfo.setUserPwd(radom.getlinkNo());
// userinfo.setUserGender(userInfoJSON.get("gender").toString());
// userinfo.setUserImg(userInfoJSON.get("avatarUrl").toString());
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// userinfo.setCreateTime(new Date());
// userService.insert(userinfo);
// } else {
// return VResponse.error(0,"解密失败");
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return VResponse.success("1",userinfo);
}
}