广告
返回顶部
首页 > 资讯 > 移动开发 >微信小程序登陆(全流程-前后端)
  • 865
分享到

微信小程序登陆(全流程-前后端)

微信小程序小程序微信 2023-08-31 18:08:03 865人浏览 八月长安
摘要

环境要求 注册一个小程序 微信开发者工具 idea(SpringBoot) 目录 项目准备 用户登陆 前端开发,传递code index.wxss index.js 后端编写,调用微信接口,获取openId 现在用户的所有信息都拿不到

环境要求

注册一个小程序

微信开发工具

idea(SpringBoot)

目录

项目准备

用户登陆

前端开发,传递code

index.wxss

index.js

后端编写,调用微信接口,获取openId

现在用户的所有信息都拿不到,只能用户自己填写


其实微信前端是可以直接请求获取openId的,但是会暴露你的key和secret

流程:前端获取code->后端调用微信接口->返回openid给前端


项目准备

打开微信开发工具,点击添加

创建小程序

  • 修改项目名称
  • 更换目录
  • 选择从网页创建好的小程序AppId
  • 选择不使用云服务
  • 模板选择基础
  • 使用javascript的基础模板

用户登陆

前端开发,传递code

首先画一个登陆按钮

index.wxml 

后端请求-响应测试登陆

index.wxss

.test_view .title{  font-weight: bold;  font-size: 18px;  color: #5F687E;  text-align: center;  margin-bottom: 10px;}.test_view button{  background-color: paleGoldenrod;}

index.js

// index.js// 获取应用实例const app = getApp()Page({  // data: {  //  user_name:"小王"  // },  clickLogin:function(){    wx.login({      success (res) {        console.log("js_code",res.code)        if (res.code) {          //发起网络请求          wx.request({            url: 'Http://localhost:8087/user/getWxInfoTest',            method: 'post',            data: {              code: res.code            }          })        } else {          console.log('登录失败!' + res.errMsg)        }      }    })  }})

后端编写,调用微信接口,获取openId

获取openId需要3个参数,appid,code,secret。

登录 微信公众平台 =>开发管理=>开发设置=>开发者Id

appId

AppSecret

其中的HttpUtils参考我的这篇

httpUtils(怕大家还要去我的博客里找,这里给懒的同学~准备了一份直接复制就可以用的)

package com.example.tx_mini_pro.tools;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalfORMedURLException;import java.net.URL;public class HttpUtils {    public static String getRequest(String httpurl) {        HttpURLConnection connection = null;        InputStream is = null;        BufferedReader br = null;        String result = null;// 返回结果字符串        try {            // 创建远程url连接对象            URL url = new URL(httpurl);                    // 通过远程url连接对象打开一个连接,强转成httpURLConnection类                    connection = (HttpURLConnection) url.openConnection();            // 设置连接方式:get            connection.setRequestMethod("GET");            // 设置连接主机服务器的超时时间:15000毫秒            connection.setConnectTimeout(15000);            // 设置读取远程返回的数据时间:60000毫秒            connection.setReadTimeout(60000);            // 发送请求            connection.connect();            // 通过connection连接,获取输入流            if (connection.getResponseCode() == 200) {                is = connection.getInputStream();                // 封装输入流is,并指定字符集                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));                // 存放数据                StringBuffer sbf = new StringBuffer();                String temp = null;                while ((temp = br.readLine()) != null) {                    sbf.append(temp);                    sbf.append("\r\n");                }                result = sbf.toString();            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            // 关闭资源            if (null != br) {                try {                    br.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (null != is) {                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            connection.disconnect();// 关闭远程连接        }        return result;    }}

springBoot请求接口,请求外部接口_springboot请求外部接口_我要用代码向我喜欢的女孩表白的博客-CSDN博客

public  static String getOpenid(String code,String appid,String secret) {// 调用接口必要的参数        StringBuilder data=new StringBuilder();// appid、secret定义在配置文件中,注入到项目里        data.append("appid="+appid+"&");        data.append("secret="+ secret+"&");        data.append("js_code="+ code+"&");        data.append("grant_type="+ "authorization_code");        String response = HttpUtils.getRequest("https://api.weixin.qq.com/sns/jscode2session?" + data);        return response;    }

本地调试需要在微信小程序中,【详情】,然后【选择不校验合法】

Controller层

package com.example.tx_mini_pro.controller;import com.alibaba.fastJSON.JSONObject;import com.example.tx_mini_pro.tools.AppConfigTools;import com.example.tx_mini_pro.tools.WechatTools;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.WEB.bind.annotation.*;@RestController@RequestMapping("/user")@Slf4jpublic class UserController {//    @Autowired//    UserService userService;    @Autowired    WechatTools wechatTools;    //    @PostMapping("/login")//    public RsJsonBean LoginUser(@RequestBody JSONObject obj){////        userService.LoginUser(obj.getString("code"));////    return null;//}    @PostMapping("/getWxInfoTest")    public String getWxInfoTest(@RequestBody JSONObject obj) {        String AppId = AppConfigTools.getWxAppId();        String AppSecret = AppConfigTools.getWxAppSecret();        JSONObject wxJson = JSONObject.parseObject(WechatTools.getOpenid(obj.getString("code"), AppId, AppSecret));        log.info("微信的返回值{}", wxJson);        return wxJson.toJSONString();    }}

拿到openId之后,其实就已经登陆了,如果用户是首次的话,那应该注册,获取用户的基本信息

现在获取用户昵称和头像,其他的很多东西,现在比较注重隐私,数据都拿不到的。

现在用户的所有信息都拿不到,只能用户自己填写

 

 

 

关于授权,如果用户拒绝授权,就得删除小程序,在重新进来

 

wx.getUserInfo,然后我得到了一个,昵称叫微信用户的东西,头像是这个

 

前端授权代码

wxml

授权头像和昵称

js

 getScope:function(){    wx.getSetting({      success(res) {        if (!res.authSetting['scope.record']) {          wx.authorize({            scope: 'scope.userInfo',            success () {              // 用户已经同意小程序使用昵称和头像功能              console.log(wx.getUserInfo())            }          })        }      }    })  }

结果.我真的对小程序很无语

 

参考:

微信小程序登录方法,授权登陆及获取微信用户手机号_微信小程序登陆_痴心阿文的博客-CSDN博客

java 后端获取微信小程序openid-CSDN博客

微信小程序获取用户openid的方法详解_javascript技巧_脚本之家

来源地址:https://blog.csdn.net/qq_38403590/article/details/129932578

--结束END--

本文标题: 微信小程序登陆(全流程-前后端)

本文链接: https://www.lsjlt.com/news/386618.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作