> 文章列表 > 微信小程序登陆(全流程-前后端)

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

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

环境要求

1.注册一个小程序

2.微信开发者工具

3.idea(springboot)

目录

项目准备

用户登陆

前端开发,传递code

index.wxss

index.js

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

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


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

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


项目准备

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

2.创建小程序

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

用户登陆

前端开发,传递code

首先画一个登陆按钮

index.wxml 

<view class="test_view"><view class="title">前后端请求-响应测试</view><view><button bindtap="clickLogin">登陆</button></view></view>

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();// 设置连接方式:getconnection.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")
@Slf4j
public class UserController {
//    @Autowired
//    UserService userService;@AutowiredWechatTools wechatTools;/* 微信小程序的登陆,如果有账号,则返回登陆成功,如果没有则返回(首次用户,需要认证)* @return*/
//    @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

<view><button bindtap="getScope">授权头像和昵称</button></view>

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技巧_脚本之家