java 实现微信授权登陆

附官方文档地址小程序登陆 | 微信开放文档

编码前准备工作:开发之前我们需要准备两个东西AppID和AppSecret,需要到微信开放平台(https://open.weixin.qq.com)注册开发者账号,并在移动应用中将我们的APP创建进去,填写对应资料后提交审核

准备工作做好后我们开始实现,我们项目用的是springBoot+mybatis框架进行的接口开发

1.第一步是由app端调起微信授权登录页面让用户进行授权操作,用户确认授权后会返回一个code,这个code就是我们后面获取授权用户信息的关键

2.拿着第一步获得的code去获取用户信息并进行登录操作,代码如下

接收微信返回参数的实体类:

package com.xk.hmo.dto.login;

import lombok.Data;

@Data
public class WxLoginInfo {

    private String openid;//用户唯一标识
    private String session_key;//会话密匙
    private String unionid;//用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回
    private Integer errcode;
    private String errmsg;

}

appId 和 appSecret:

package com.xk.hmo.service.mobile.config;

/**
 * 小程序微信登陆配置文件
 * @author zhangt
 */
public class WxConstant {
    //小程序appid
    public static final String appid = "xxxxxxxxxxxxxxxx";
    //小程序密匙
    public static final String secret = "xxxxxxxxxxxxxxxxxxxxxxxx";
}

pom文件引入:

<dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
</dependency>

FastJsonUtil:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.xml.crypto.dsig.keyinfo.KeyValue;

public class FastJsonUtil {
    private static final SerializeConfig config = new SerializeConfig();
    private static final SerializerFeature[] features;

    private FastJsonUtil() {
        throw new AssertionError();
    }

    public static String toJSONString(Object obj) {
        return JSON.toJSONString(obj, config, features);
    }

    public static String toJSONNoFeatures(Object obj) {
        return JSON.toJSONString(obj, config, new SerializerFeature[0]);
    }

    public static Object toBean(String str) {
        return JSON.parse(str);
    }

    public static <T> T toBean(String str, Class<T> clazz) {
        return JSON.parseObject(str, clazz);
    }

    public static <T> Object[] toArray(String str) {
        return toArray(str, (Class)null);
    }

    public static <T> Object[] toArray(String str, Class<T> clazz) {
        return JSON.parseArray(str, clazz).toArray();
    }

    public static <T> List<T> toList(String str, Class<T> clazz) {
        return JSON.parseArray(str, clazz);
    }

    public static Object beanToJson(KeyValue keyvalue) {
        String textJson = JSON.toJSONString(keyvalue);
        Object objectJson = JSON.parse(textJson);
        return objectJson;
    }

    public static Object strToJson(String str) {
        Object objectJson = JSON.parse(str);
        return objectJson;
    }

    public static Map stringToCollect(String str) {
        Map m = JSONObject.parseObject(str);
        return m;
    }

    public static String collectToString(Map map) {
        String str = JSONObject.toJSONString(map);
        return str;
    }

    static {
        config.put(Date.class, new JSONLibDataFormatSerializer());
        config.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
        features = new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullStringAsEmpty};
    }
}

/**
     * 微信授权登陆
     *
     * @param code
     * @throws IOException
     */
    @PostMapping("/wxLogin")
    @ResponseBody
    protected ResultPO wxLogin(@RequestParam String code) {
        HttpClient httpclient = new HttpClient();
        GetMethod get = new GetMethod("https://api.weixin.qq.com/sns/jscode2session?appid="+ WxConstant.appid +"&secret="+WxConstant.secret +"&js_code="+ code +"&grant_type=authorization_code");
        String info ="";
        try {
            httpclient.executeMethod(get);
            info = new String(get.getResponseBody(), "utf-8");
        }catch (Exception e){
        	//抛出异常 微信授权失败,请稍后再试
            throw new HMOException(CommonErrorCode.E100035);
        }
        log.error(info);
        WxLoginInfo wxLoginInfo = FastJsonUtil.toBean(info, WxLoginInfo.class);
        
        ResultPO success = ResultPO.success();
        if (wxLoginInfo.getErrcode() != null){
            success.setErrorMsg(wxLoginInfo.getErrcode().toString(), wxLoginInfo.getErrmsg());
        }else{
            success.setData(wxLoginInfo);
            //成功获取到授权,根据个人业务需求写就可以了。。。
        }
        return success;
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值