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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章