uniapp实现微信登录-从0-1(兼后台代码)

一.大致实现思路

        1.给微信图标绑定一个触发事件,实现微信登录,然后再调用小程序的API。

        参考官方文档:https://uniapp.dcloud.net.cn/api/plugins/login.html

        2.调用wx.getUserProfile()方法,这个方法是微信自带的,关于是否微信获取用户信息的权限。

        3.用户同意后,在wx.getUserProfile()的回调中再次调用wx.login()这个API。会返回一个code 这个code每次调用都会刷新一次,(注意:不能携带code进行两次请求,否则会报错,40029)

        4. 然后前端发送请求携带code到后端,你也可以携带用户信息对象,在下面代码会演示。

        5.后端开始根据这个code和你的小程序的AppId和Appsecret调用微信的服务器来获得openId(这是每个用户登录的唯一id,后期可以根据openid查询登录信息,而不会重复)

        6.获取到openid后就可以进行自定义业务逻辑了。

二.下面开始演示代码

        前端:uniapp

        2.1 首先给微信图标绑定事件

<image @click="weixinLo()" class="icon" src="../../static/微信.png" ></image>

        2.2 js代码:主要思路

                1.主要逻辑是先判断是否含有token,这个是验证登录的标识         

                2.判断是否用户收授权登录       

                3.用户同意后调用wx.login()方法,返回code和登录对象信息返回给后端接口。

weixinLo(){
				let that = this
				let token = uni.getStorageSync('token')
				wx.showLoading({
					title: '加载中',
				})
				console.log(token)
				if(token){
					//如果已经有token,说明用户已经登录,跳转到指定页面
					wx.reLaunch({
						url: "../index/index"
					})
				}else{
					// 未登录
					wx.getUserProfile({
						desc: '用于完善用户资料',
						success(res) {
							that.userInfo = res.userInfo
							if (res.errMsg == "getUserProfile:ok") {
								let code = null
								wx.login({
									success(e) {
										code = e.code
										let params = {};
										params.code = code; //用户code  注:用户的code每次登录都是随机的,所以不需要进行存储
										params.avatar = res.userInfo.avatarUrl; //用户头像
										params.nickname = res.userInfo.nickName; //用户微信名
										params.sex = res.userInfo.gender; //用户性别 0为未知,1为男,2为女
										wx.request({
											url: 'http://localhost:8010/educmsl/api/ucenterstu/wx/login',
											method: 'POST',
											data: params,
											success(res) {
												if(res.data.success){
													 //存储用户信息
													uni.setStorageSync('token', res.data.data.token);
													uni.reLaunch({
														url: '../my/my'
													})
												}else{
													console.log(res.data.message)
												}
											}
										})
									}
								})
							}
						}
					})
				}
			},

 后端:  java

         2.3. 写接口先得预备工作,先获得小程序的appid与密钥

                主要思路:  创建一个获取小程序appid与密钥的类

                实现步骤: 通过springboot的组件@Component注解,然后类实现 InitializingBean 这个接口(是用来初始化bean对象的作用)。

                注意:这里使用了@Component注解,最好在启动类上加上             @ComponentScan(basePackages={"com.laoyang"})这个注解,用来扫描我们自己的组件。

package com.laoyang.educms.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author:Kevin
 * @create: 2022-11-03 15:00
 * @Description: 小程序密钥与id
 */
@Component
public class Wxmini implements InitializingBean {

    @Value("${wxMini.appId}")
    private String appid;

    @Value("${wxMini.secret}")
    private String secret;

    public static String APPID;

    public static String SECRET;

    @Override
    public void afterPropertiesSet() throws Exception {
        APPID = appid;
        SECRET = secret;

    }
}

        2.3.1:然后还要在配置文件添加appid与密钥

                        (这里需要去微信公众平台查看个人appid与密钥

        2.4:主要接口开发

                主要思路

                1.  后台接收到前端的code,然后携带appid和密钥发送请求到微信的服务器。

                2.  然后响应获得openid,实现自定义逻辑,说下我的逻辑。

                3.  先new用户对象,将前端授权获得的信息封装到此对象中,然后根据opendi查询是否有这个对象,有就执行更新信息操作,没有就添加信息。然后生成token返回给前端。

https://api.weixin.qq.com/sns/jscode2session?appid=" + Wxmini.APPID + "&secret=" + Wxmini.SECRET + "&js_code=" + code + "&grant_type=authorization_code";
package com.laoyang.educms.controller;

import com.alibaba.fastjson.JSONObject;
import com.laoyang.CommonUtils.JwtUtils;
import com.laoyang.CommonUtils.R;
import com.laoyang.educms.entity.UcenterMember;
import com.laoyang.educms.service.UcenterMemberService;
import com.laoyang.educms.utils.WeChatUtil;
import com.laoyang.educms.utils.Wxmini;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author:Kevin
 * @create: 2022-11-03 12:26
 * @Description: 微信小程序登录与退出
 */
@RestController //注意这里没有配置 @RestController
@RequestMapping("/educmsl/api/ucenterstu/wx")
public class WxApiStuController {

    @Autowired
    private UcenterMemberService memberService;


    @PostMapping("/login")
    public R wxlogin(@RequestBody UcenterMember user){

        String code = user.getCode();
        if (code == "" || "".equals(code)){
            return R.error("code不能为空!");
        }else {
            //微信接口服务,通过调用微信接口服务中jscode2session接口获取到openid和session_key
                String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Wxmini.APPID + "&secret=" + Wxmini.SECRET + "&js_code=" + code + "&grant_type=authorization_code";
            String str = WeChatUtil.httpRequest(url, "GET", null); //调用工具类解密
            JSONObject jsonObject= JSONObject.parseObject(str);
            String openid = (String) jsonObject.get("openid");
            if(openid != null && !"".equals(openid)){
                //登录成功
                UcenterMember member = new UcenterMember();
                member.setNickname(user.getNickname());
                member.setOpenid(openid);
                member.setAvatar(user.getAvatar());
                member.setGmtCreate(new Date());
                member.setGmtModified(new Date());

                UcenterMember mymember = memberService.getByOPenId(openid);
                if (mymember == null){
                    //就是第一次登录,向数据库插入信息
                    //向数据库中插入一条记录
                    memberService.save(member);
                }else {
                    //更新数据
                    member.setId(mymember.getId());
                    memberService.updateById(member);

                }

                //使用jwt生成token,
                String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

                return R.ok().data("token",jwtToken);
            }


        }




        return R.error("登录失败");
    }
}

        小结:

                首先说下我开发中遇到的问题,希望大家避坑,

        1.在写Controller时没有添加@RestController,返回前端json格式的注解,所以刚开始时后台响应成功了,前端却报404.

        2.code因为是一次性的,所以不能在请求里的请求携带code,否则微信服务器会响应40029的报错代码信息。因此就在wx.login()的回调函数中请求后端接口并携带code就ok了。

                

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Uniapp是一款基于Vue.js框架的跨平台开发工具,它支持同时开发多个平台的应用,其中包括微信小程序。在Uniapp中,我们可以使用uni.uploadFile()方法上传图片。 上传图片前,我们需要先获取到图片的本地路径,可以通过uni.chooseImage()方法选择图片并获取到本地路径: uni.chooseImage({ count: 1, success: function (res) { var tempFilePaths = res.tempFilePaths; } }); 接下来,我们就可以使用uni.uploadFile()方法上传图片了。具体参数说明如下: uni.uploadFile({ url: '上传接口的地址', filePath: '要上传的文件路径', name: '上传文件对应的 key', formData: {'其他额外的formdata'}, success: res => {}, fail: () => {}, complete: () => {} }); 其中,url为上传接口的地址;filePath为要上传的文件路径,即上一步获取到的本地路径;name为上传文件对应的key,可以根据后台的要求进行修改;formData为其他额外的formdata,可以根据后台的要求进行传递。success、fail和complete为上传成功、失败和完成后的回调函数。 上传图片需要注意的是,需要在微信小程序的后台配置好上传接口的请求域名并获取到上传的token等信息,否则上传会失败。 ### 回答2: 要实现uniapp微信小程序上传图片,我们需要了解一些相关的知识点和实现步骤。 首先,我们需要使用uniapp官方提供的wx.chooseImage()接口来获取用户选择的图片并且展示出来。代码如下: ``` uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: (res) => { this.tempFilePaths = res.tempFilePaths[0] this.imgSrc = this.tempFilePaths } }) ``` 其中count表示选择的图片数量,sizeType表示图片尺寸,sourceType表示图片来源,success表示成功回调函数,tempFilePaths是选择的图片本地文件路径。 然后,在获取到图片路径后,我们需要借助wx.uploadFile()接口来实现上传图片。具体实现代码如下: ``` uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: (res) => { this.tempFilePaths = res.tempFilePaths[0] this.imgSrc = this.tempFilePaths uni.uploadFile({ url: '上传图片的接口地址', filePath: this.tempFilePaths, name: 'file', formData: { 'user': 'test' }, success: (res) => { console.log(res) } }) } }) ``` 其中url是上传图片的接口地址,filePath是要上传的图片的本地文件路径,name表示上传图片对应的key值,formData表示要一起上传的数据,success表示成功回调函数。 需要注意的是,上传图片的接口地址和具体的formData数据格式需要我们自己根据后台需求来进行处理。 以上就是实现uniapp微信小程序上传图片的原理和具体实现步骤,可以根据具体需求进行修改和调整。 ### 回答3: Uniapp是一款基于Vue.js框架开发的跨平台应用开发框架,用它我们可以快速简单地开发出多种类型的应用。其中,Uniapp集成了微信小程序的功能,可以通过Uniapp开发界面,同时发布到多个平台,如微信小程序、H5、iOS和安卓等。 在Uniapp中,小程序上传图片涉及到两个方面,一个是前端页面的实现,另一个是后端的接收和处理。下面我们分别来看一下。 一、前端页面的实现 1.首先,我们需要在页面中引入uni-com*ponents组件: ```html <uni-com*ponents @choose="chooseImage" :count="1">选择图片</uni-com*ponents> ``` 其中,chooseImage是我们自定义的方法名,被触发时执行选择图片的功能。 2.接着,在js代码文件中定义chooseImage方法: ``` chooseImage() { uni.chooseImage({ count: 1, success: chooseResult => { uni.uploadFile({ url: 'http://localhost:3000/upload', filePath: chooseResult.tempFilePaths[0], name: 'image', formData: { user: '' }, success(uploadResult) { console.log(uploadResult.data); } }); } }); } ``` 这里我们使用uni.chooseImage选择图片,然后调用uni.uploadFile上传图片,其中url是后端接口地址,filePath是临时文件路径,name是上传文件的key值,formData是一些额外的参数,success为上传成功的回调函数。 二、后端接收和处理 后端接收和处理图片涉及到Node.js和Express框架的使用,这里我们简单介绍一下。 1.首先,在服务器端使用npm安装multer和cors插件,分别用于文件上传和跨域处理。 ``` npm install multer cors ``` 2.在Node环境下创建upload.js文件,引入express、multer和cors插件,并定义上传路径和上传文件大小限制等相关参数,代码如下: ``` const express = require('express'); const path = require('path'); const multer = require('multer'); const cors = require('cors'); const app = express(); app.use(cors()); const storage = multer.diskStorage({ destination: './uploads/', filename: function(req, file, cb) { cb(null, Date.now() + '-' + file.originalname); } }); const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 2 } // 上传文件大小限制,默认为2MB }); app.post('/upload', upload.single('image'), function(req, res) { const file = req.file; if (!file) { const error = new Error('Please upload a file'); error.httpStatusCode = 400; return next(error); } res.send(file); }); app.listen(3000, function() { console.log('Server started on port 3000'); }); ``` 这里我们使用express框架创建了一个服务器,并通过multer中间件实现上传文件的功能,同时使用cors插件解决跨域问题。我们在/upload接口中通过upload.single()实现单文件上传,同时通过res.send返回上传成功的文件信息。 3.最后,我们启动Node.js服务器,在小程序中选择并上传图片,我们可以在控制台中看到文件上传的结果。 总结: 通过以上代码,我们可以实现Uniapp微信小程序上传图片的功能,其中主要分为前端页面的实现和服务器端的处理。在实际使用中,我们可以根据实际需求进行不同的调整和优化,以便更好地满足应用需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值