栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

uniappH5+springboot微信授权登录获取用户数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

uniappH5+springboot微信授权登录获取用户数据

uniappH5+springboot微信授权登录获取用户数据

准备工作

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

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

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

  1. html页面代码






  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);
            //请求获取userInfo
            String 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 {
    //返回状态码,为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;
    }

    @Override
    public 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;


public class HttpUtil {
    public static String doGet(String urlPath, HashMap params)
            throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");

            Set> set = params.entrySet();
            for (Map.Entry 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 ==
            // 200
            BufferedReader 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 param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder 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);
            // 判断返回状态是否为200
            if (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);
    }





}

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949366.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号