uniappH5+springboot微信授权登录获取用户数据(非静默授权)

微信网页授权开发文档

准备工作

微信公众号appid和appSecret及配置相关的ip白名单

配置网页授权域名,具体操作看里面的提示

一. 前端发送请求微信接口获取code

  1. html页面代码
<template><view class="main"><!-- 我的 --><view class="title"><view class="containers" v-if="isLogin"><image :src="headimgurl"></image><button>{{nickname}}</button></view><view class="containers" v-else><image src="/static/images/login.png"></image><button open-type="getUserInfo" @click="login()">点击登录</button></view></view><view class="quit" @click="exitLogin()" v-if="isLogin">退出登录</view></view></template><script>export default {data() {return {isLogin: false,nickname: "", //用户名headimgurl: "", //头像openid: "", //openid}},onLoad() {window.onpageshow = function (evt) {setTimeout(function(){if(evt.persisted){location.reload(true);}});}var res_openid = uni.getStorageSync("openid")this.openid = res_openidif (this.openid != "") {this.nickname = uni.getStorageSync("nickname");this.headimgurl = uni.getStorageSync("headimgurl");this.openid = uni.getStorageSync("openid");this.isLogin = true}},onShow() {this.checkWeChatCode()},methods: {//方法:用来提取codegetUrlCode(name) {return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null},//检查浏览器地址栏中微信接口返回的codecheckWeChatCode() {var that = thislet code = this.getUrlCode('code')let res_code = uni.getStorageSync("code")if(res_code!=code){if(code != null && code != ""){if(this.openid != ""){uni.showToast({title: '已登陆',icon:'none',duration: 1000})return;}let res =  this.$myRequest({url: 'wechat/apiLoginController/getOpenId',method:'get',data: {code:code}}).then(res =>{if(res.data.errcode == 0){//.then是接收正确返回的信息this.openid = res.data.data.openiduni.setStorageSync("nickname",res.data.data.nickname)//用户名uni.setStorageSync("headimgurl",res.data.data.headimgurl)//头像uni.setStorageSync("openid",res.data.data.openid)//openidwindow.history.back()uni.reLaunch({url:'./my'})}else{window.history.back()uni.showToast({title: '登录失败'+err.data.data,icon:'none',duration: 1000})}}).catch(err =>{window.history.back()// .catch 返回报错信息uni.showToast({title: '请求异常' + err.errMsg,icon: 'none',duration: 1500})})}}else{//两个code相等window.history.back()uni.showToast({title: "已授权登录...",icon:'none',duration: 4000})}},login() {//请求微信接口,用来获取codelet local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址let appid = ''//这里填写自己微信公众号的appid//通过微信官方接口获取code之后,会重新刷新设置的回调地址【redirect_uri】,之后会继续进入到onload()方法location.href ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+local+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"},exitLogin() {var that = thisuni.showModal({title: '提示',content: '你确定退出登录吗?',success(res) {if (res.confirm) {that.isLogin = falseuni.removeStorageSync("nickname");uni.removeStorageSync("headimgurl");uni.removeStorageSync("openid");uni.showToast({title: '退出成功',icon: 'none',duration: 1000})setTimeout(()=>{uni.reLaunch({url:'../index/anotherIndex'})},1000)}}})},}}
</script><style>.main {background: #f2f2f2;position: absolute;left: 0px;top: 0px;right: 0px;bottom: 0px;margin: 0px;padding: 0px;color: #2C405A;}.title{height: 380rpx;background-image: url(../../static/images/my_bg.png);background-size: 100% 100%;}.title .containers {height: 100%;margin: auto;text-align: center;}.title .containers image {margin-top: 70rpx;width: 160rpx;height: 160rpx;border-radius: 50%;}.title .containers button {color: #222222;background: none;display: block;padding: none;}button::after { border: none }.main .quit {text-align: center;padding: 40rpx 0px;color: #a1a1a1;margin-top: 20px;} </style>
  1. myRequest 请求工具类

创建request.js写入如下代码

// 定一个常量 存储请求地址
export const BASE_URL = 'hhttp://localhost:8901/'//springboot接口路径,上线这里配置成域名就好
export const myRequest = (options)=>{return new Promise((resolve, reject)=>{// 封装主体:网络请求uni.request({url: BASE_URL + options.url,header: {},data: options.data || {},      method: options.method || 'GET',// 默认值GET,如果有需要改动,在options中设定其他的method值success: (res) => {// console.log(res.data);     // 控制台显示数据信息resolve(res)},fail: (err) =>{// 页面中弹框显示失败uni.showToast({title: '请求接口失败',icon:'none',duration: 2000})// 返回错误消息reject(err)}})})
}

3.全局挂载requests.js中的myRequest方法

main.js中写入如下代码

import App from './App'
import Vue from 'vue'
import store from './store/index.js'
import uView from 'uview-ui'import { myRequest } from './utils/request.js';//自己创建的request.js路径
Vue.config.productionTip = false
// vuex
Vue.prototype.$store = store
// 引用uView
Vue.use(uView)// 挂载到全局,让所有的页面都能调用myRequest方法
Vue.prototype.$myRequest = myRequest
App.mpType = 'app'
const app = new Vue({...App,store
})
app.$mount()

二. 通过code获取相关的微信用户头像等数据

import cc.jinjun.febs.common.controller.BaseController;
import cc.jinjun.febs.common.utils.HttpUtil;
import cc.jinjun.febs.pay.wechat.WechatEnum;
import cc.jinjun.febs.wechat.entity.ResultData;
import cc.jinjun.febs.wechat.entity.WxUserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import java.io.IOException;//获取微信用户openid唯一标识
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/wechat/apiLoginController")
@CrossOrigin
public class ApiLoginController extends BaseController {//获取微信小程序openid,user等信息@ResponseBody@GetMapping("/getOpenId")public ResultData getOpenId(String code) throws IOException {try {String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +"?appid=" + WechatEnum.appId +//WechatEnum.appId更换成自己的appid"&secret=" + WechatEnum.appSecret +//WechatEnum.appSecret 更换成自己的appSecret"&code=" + code +"&grant_type=authorization_code";String result_url = HttpUtil.doPost(url);System.out.println("请求获取access_token:" + result_url);//返回结果的json对象JSONObject resultObject = JSON.parseObject(result_url);//请求获取userInfoString infoUrl = "https://api.weixin.qq.com/sns/userinfo" +"?access_token=" + resultObject.getString("access_token") +"&openid=" + resultObject.getString("openid") +"&lang=zh_CN";String infoUrl_url = HttpUtil.doPost(infoUrl);JSONObject userJsonObject = JSON.parseObject(infoUrl_url);WxUserInfo wxUserInfo = new WxUserInfo(userJsonObject.getString("nickname"), userJsonObject.getString("headimgurl"), userJsonObject.getString("openid"));return new ResultData(0, "登录成功", wxUserInfo);} catch (Exception e) {return new ResultData(501, "登录失败", e.getMessage());}}}

WxUserInfo 类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class WxUserInfo {private String nickname;//用户名private String headimgurl;//头像private String openid;//openid}

ResultData 类

public class ResultData<T> {//返回状态码,为0表示结果正确,不为0表示结果异常private Integer errcode;//结果描述private String errmsg;//返回数据private T data;public ResultData() {}public ResultData(Integer errcode, String errmsg, T data) {this.errcode = errcode;this.errmsg = errmsg;this.data = data;}public Integer getErrcode() {return errcode;}public void setErrcode(Integer errcode) {this.errcode = errcode;}public String getErrmsg() {return errmsg;}public void setErrmsg(String errmsg) {this.errmsg = errmsg;}public T getData() {return data;}public void setData(T data) {this.data = data;}@Overridepublic String toString() {return "ResultData{" +"errcode=" + errcode +", errmsg='" + errmsg + '\'' +", data=" + data +'}';}
}

HttpUtil 类

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpStatus;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;/*** @ClassName: HttpUtil* @USER: Administrator* @DATE: 2020/4/21* @TODO:**/
public class HttpUtil {public static String doGet(String urlPath, HashMap<String, Object> params)throws Exception {StringBuilder sb = new StringBuilder(urlPath);if (params != null && !params.isEmpty()) { // 说明有参数sb.append("?");Set<Map.Entry<String, Object>> set = params.entrySet();for (Map.Entry<String, Object> entry : set) { // 遍历map里面的参数String key = entry.getKey();String value = "";if (null != entry.getValue()) {value = entry.getValue().toString();// 转码value = URLEncoder.encode(value, "UTF-8");}sb.append(key).append("=").append(value).append("&");}sb.deleteCharAt(sb.length() - 1); // 删除最后一个&}URL url = new URL(sb.toString());HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000); // 5s超时conn.setRequestMethod("GET");if (conn.getResponseCode() == HttpStatus.OK.value()) {// HttpStatus.SC_OK ==// 200BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));StringBuilder sbs = new StringBuilder();String line;while ((line = reader.readLine()) != null) {sbs.append(line);}return sbs.toString();}return null;}public static String doPost(String url, Map<String, Object> param) {// 创建Httpclient对象CloseableHttpClient httpclient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse response = null;try {// 创建uriURIBuilder builder = new URIBuilder(url);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key).toString());}}URI uri = builder.build();// 创建http Post请求HttpPost httpPost = new HttpPost(uri);// 执行请求response = httpclient.execute(httpPost);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {resultString = EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpclient.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}public static String doGet(String url) throws Exception {return doGet(url, null);}public static String doPost(String url) {return doPost(url, null);}}

maven

<!-- HTTP Client --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
<!--  fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version><scope>compile</scope></dependency>
<!-- commons工具 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.8.0</version>
</dependency>

注意
完成代码后将后端项目部署到微信公众号IP白名单对应的服务器运行,不然获取不到access_token

前端部署后要分配域名,域名跟网页授权域名对应,后端项目也可以分配域名

多多指教,共同进步丫

uniappH5+springboot微信授权登录获取用户数据(非静默授权)相关推荐

  1. 微信小程序授权登录获取用户信息详解

    今天来说一下微信小程序的授权登录获取用户信息,首先我们看微信提供的小程序开发文档: https://blog.csdn.net/qq_41971087/article/details/82466647 ...

  2. Spring boot 项目(十三)——实现微信公众号授权登录获取用户信息

    引言 微信公众号开发中,必不可少的一环:公众号授权登录.获取微信用户信息 前期准备 内网渗透=>生成本地指定端口映射的外网域名 链接:内网渗透工具natapp使用详解 域名生成之后修改yml文件 ...

  3. Android之QQ授权登录获取用户信息

    有时候我们开发的app需要方便用户简单登录,可以让用户使用自己的qq.微信.微博登录到我们自己开发的app. 今天就在这里总结一下如何在自己的app中集成QQ授权登录获取用户信息的功能. 首先我们打开 ...

  4. springboot 微信小程序获取用户手机号 最新方式

    springboot 微信小程序获取用户手机号 直接开整!!! 现在有两种方式获取微信用户的手机号 第一种 这种方式比较旧了,也能获取到手机号,但不建议使用. 1.前端调用wx.login()(官方的 ...

  5. 基于Spring Boo微信公众号授权登录获取用户信息(附带完整源码)

    简介 微信公众号开发中,必不少可少的一环:公众号授权登录.获取微信用户信息. 本地完整运行环境准备 内网渗透=>生成本地指定端口映射的外网域名 传送门:内网渗透工具Natapp使用详解 域名生成 ...

  6. 微信小程序授权登录获取用户信息并保存至缓存用于下次登录

    1.获取用户信息 wx.getUserProfile(Object object) 获取用户信息.页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗 ...

  7. java实现微信公众号授权登录获取用户信息(一)

    参考文章:https://blog.csdn.net/Santiago_M/article/details/79109154 : https://www.cnblogs.com/jilu/p/6123 ...

  8. 微信登录——授权登录获取用户信息

    引言 实现微信扫码登录关键之处就是获取到微信用户信息,那么这就涉及到了微信授权,通过微信授权我们可以获取到用户信息:微信官方文档写的还是比较详细的,但是没有代码演示,这里我就用代码演示一下如何实现微信 ...

  9. springboot小程序授权登录获取用户手机号

    controller: /*** 授权获取用户手机号** @param mobile* @param type* @return*/@PostMapping("/getPhone" ...

最新文章

  1. XSLT教程 [转]
  2. 高内聚、低耦合的含义是什么?
  3. 成本中心的费用计划/KP06
  4. java逻辑移位和算术移位,关于对移位运算的理解
  5. 红米手机停在机器人这里_iQOO Z1和红米K30 至尊纪念版,谁更值得选择?
  6. Python中的yield详解
  7. 聚合maven+spring-boot打包可执行jar
  8. curl命令php,php生成curl命令行的方法
  9. 微信小程序之页面跳转
  10. JAVA的if用法比如if(...){} 和if()没有区别
  11. EDA与VHDL题目——38译码器
  12. 六大排序算法:插入排序、希尔排序、选择排序、冒泡排序、堆排序、快速排序
  13. c# 试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
  14. LTspice中 Voltage Controlled Switches的使用方法
  15. DC-DC电源市场现状及未来发展趋势分析
  16. 科普贴,告诉大家SGLTE、SVLTE、CSFB、SRLTE的意思
  17. [vue] 无缝滚动 vue-seamless-scroll 滚动表格
  18. 视频水印怎么去掉?有什么好的去水印工具吗?
  19. 麻省理工学院计算机博士毕业,努力比起点更重要!有高职院校学生,拿下麻省理工大学博士offer...
  20. 医学影像处理相关软件及python包

热门文章

  1. sfdisk 分区命令
  2. PostgreSQL安全基线
  3. Slf4j之MDC应用
  4. android 刷机攻略总览
  5. C语言中文件的打开与关闭
  6. 服务器推送技术原理分析及dwr框架简单的使用
  7. 虚拟磁带库(VTL)简介
  8. 小程序技术,打开跨端管理的思路,提高客户满意度和忠诚度
  9. 【编程马拉松】【026-是男人就下100层】
  10. 阿里动态规划笔试题事后总结