微信小程序登陆

作者: gu_lao_rou-p 分类: springBoot,Vue3,wx 发布时间: 2022-02-15 18:43

https://mp.weixin.qq.com/wxamp/

在开发管理的开发设置里拿到AppID(小程序ID),和AppSecret(小程序密钥)

更改后端yml文件:

wx:
  app-id: 填写AppID(小程序ID)
  app-secret: 填写AppSecret(小程序密钥)

进入service层添加:

@Service
public class UserService {
    @Value("${wx.app-id}")
    private String appId;


    @Value("${wx.app-secret}")
    private String appSecret;

    private String getOpenId(String code){
        /**
         * @param code: 微信的临时凭证
         * @return String
         * @author Gavin
         * @description 通过微信的临时凭证获取OpenId
         * @created 2022/2/13 12:11
         **/
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");

        return openId;
    }
    public String test(TestReq req){
        String openId = getOpenId(req.getCode());
        return openId;
    }
}

controller层:

@PostMapping("test")
public R test(@RequestBody TestReq req){
    return R.ok().put("code", userService.test(req));
}

来到前端

在manifest.json里,选择微信小程序配置,在微信小程序AppId下填写AppId

前端:

<template>
	<view>
		<view>
			<button @click="button">GULAO</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {

		},
		methods: {
			button(){
				let that = this;
				uni.login({
					provider: "weixin",
					success: function(resp) {
						let code=resp.code
						console.log(code);
						uni.getUserProfile({
						  desc: '获取用户信息',
						  success: function (resp) {
							// this.loading;
							let nickName = resp.userInfo.nickName;
							let avatarUrl = resp.userInfo.avatarUrl;
							console.log(resp)
							var data = {
								"code":code,
								"nickName":nickName,
								"avatarUrl":avatarUrl
							}
							uni.request({
								url: "http://localhost:8080/user/test",
								data:data,
								method:"POST",
								success: (res) => {
									console.log(res);
								},
								fail: function(e) {
								    console.log('error in...')
								    // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
								    
								}
							})
						}
					})
				}
			})
		}
	},
}
</script>

<style>

</style>

注意⚠️:

更改请求网址,localhost处填写所处wifi的IP,localhost后面的端口也要填

需要运行到微信小程序,并且使用真机调试,不然无法取得数据


Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 26

Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 27

Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 28
标签云