Weixin4j微信开发网页授权获取openid案例

前言

weixin4j网页静默授权获取openid案例

**说明:**微信网页授权基础知识请参考官方文档。

静默授权获取OpenId

本 示例基于weixin4j开发,weixin4j是Java微信开发SDK,官网http://www.weixin4j.org/
本示例只演示思路,并抽象出了一个授权的公共方法,仅供参考

第一步:创建Weixin对象
第二步:使用Weixin.sns()获取组件SnsComponent
第三步:生成静默授权获取OpenId的跳转链接
第四步:从请求中获取微信授权code
第五步:用code换取微信用户OpenId


import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.component.SnsComponent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * BaseController
 *
 * @author yangqisheng
 * @date 2019/07/17
 */
public class BaseController {

    private Weixin weixin = new Weixin();

    /**
     * 校验网页授权并获取openid
     *
     * @param request 请求对象
     * @param response 输出对象
     * @param returnUrl 网页授权后跳转回链接
     * @return 是否已获取openid
     * @throws IOException
     */
    private boolean validateOAuthOpenId(
            HttpServletRequest request, HttpServletResponse response,
            String returnUrl) throws IOException, WeixinException {
        //从session中获取openid
        Object oauth_openid = request.getSession().getAttribute("openid");
        //第一次访问,判断是否存在openid,不存在则说明没有进行授权访问,进行授权访问
        if (oauth_openid == null) {
            //获取Sns组件
            SnsComponent snsComponent = weixin.sns();
            //获取code,换取openid
            String code = request.getParameter("code");
            //如果没有获取到,则说明是直接访问页面链接,进行匿名获取
            if (code == null || code.equals("")) {
                //生成静默授权获取openid跳转链接
                String url = snsComponent.getOAuth2CodeBaseUrl(returnUrl);
                //跳转到微信授权页面
                response.sendRedirect(url);
                return false;
            } else {
                //获取授权得到的openid
                String openid = snsComponent.getOpenId(code);
                //设置当前用户
                request.getSession().setAttribute("openid", openid);
                //重定向到URL
                response.sendRedirect(returnUrl);
                return false;
            }
        }
        return true;
    }
}

步骤讲解

创建微信对象并获取SnsCompoment组件

我们引入开发包

<dependency>
     <groupId>org.weixin4j</groupId>
     <artifactId>weixin4j</artifactId>
    <version>0.1.5</version>
</dependency>

这一步可以有很多方法,比如案例中的直接

Weixin weixin =  new Weixin()

也可以使用

Weixin weixin = WeixinBuilder.newInstance().build();

如果你使用springmvc开发的话,也 可以引入weixin4j-spring

<dependency>
    <groupId>org.weixin4j</groupId>
    <artifactId>weixin4j-spring</artifactId>
    <version>1.0.0</version>
</dependency>

那么这个适合你就可以使用这种方式来创建weixin对象了
xml方式,在applicationContext.xml中配置bean

<!-- 定义微信工厂Bean -->
<bean id="weixinFactory" class="org.weixin4j.spring.WeixinFactoryBean">
    <!--property name="weixinConfig" ref="weixinConfig" /-->
    <!--property name="weixinPayConfig" ref="weixinPayConfig" /-->
    <!--property name="tokenLoader" ref="myTokenLoader" /-->
    <!--property name="ticketLoader" ref="myTicketLoader" /-->
</bean>
<!-- 初始化微信模板Bean -->
<bean id="weixinTemplate" class="org.weixin4j.spring.WeixinTemplate">
    <constructor-arg index="0" ref="weixinFactory" ></constructor-arg>
</bean>

在代码中使用注解获取

@Autowired
private WeixinTemplate weixinTemplate;

对的 ,你没看错,在springmvc里,我们的Weixin对象被WeixinTemplate代理了,所以我们这样获取SnsComponent

SnsComponent snsComponent = weixinTemplate.sns();

如果你使用的是spring-boot,那就更简单了
直接引入spring-boot的配置

<dependency>
    <groupId>org.weixin4j.spring.boot</groupId>
    <artifactId>weixin4j-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

在代码中使用注解即可获取

@Autowired
private WeixinTemplate weixinTemplate;

更多weixin4j的配置请参考这篇文章https://blog.csdn.net/yakson/article/details/82108649

生成网页授权获取openid跳转链接

关于网页授权的两种scope的区别说明
1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
3、用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(即openid)关注了公众号后,才能调用成功的。

SnsCompomen组件里提供了静默授权(snsapi_base)和安全授权(snsapi_userinfo)

String url = snsComponent.getOAuth2CodeBaseUrl(returnUrl);

这段返回的就是微信 静默授权链接地址

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

用code换取openid

这一步是最简单的 ,看代码就清楚了

String openid = snsComponent.getOpenId(code);

好了 ,网页授权获取openid就讲到这里,另附一小段安全授权获取用户头像代码

安全授权获取微信用户昵称、头像

    /**
     * 校验网页授权并获取微信用户信息
     *
     * @param request 请求对象
     * @param response 输出对象
     * @param returnUrl 网页授权后跳转回链接
     * @return 是否已获取openid
     * @throws IOException
     */
    private boolean validateSnsUser(
            HttpServletRequest request, HttpServletResponse response,
            String returnUrl) throws IOException, WeixinException {
        //从session中获取openid
        Object oauth_openid = request.getSession().getAttribute("openid");
        //第一次访问,判断是否存在openid,不存在则说明没有进行授权访问,进行授权访问
        if (oauth_openid == null) {
            //获取Sns组件
            SnsComponent snsComponent = weixin.sns();
            //获取code,换取openid
            String code = request.getParameter("code");
            //如果没有获取到,则说明是直接访问页面链接,进行匿名获取
            if (code == null || code.equals("")) {
                //生成静默授权获取openid跳转链接
                String url = snsComponent.getOAuth2CodeUserInfoUrl(returnUrl);
                //跳转到微信授权页面
                response.sendRedirect(url);
                return false;
            } else {
                //获取授权得到微信用户信息
                SnsUser snsUser = snsComponent.getSnsUserByCode(code);
                System.out.println(snsUser.getNickname());
                System.out.println(snsUser.getHeadimgurl());
                //设置当前用户
                request.getSession().setAttribute("openid", snsUser.getOpenid());
                //重定向到URL
                response.sendRedirect(returnUrl);
                return false;
            }
        }
        return true;
    }

欢迎加入weixin4j官方VIP群学习,QQ群:473227872

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值