1. 程式人生 > >微信公眾號授權登入weixin4j開發

微信公眾號授權登入weixin4j開發

  • 登入微信公眾號配置網頁授權目錄
    這裡寫圖片描述
  • 在專案中引入maven依賴
<dependency>
  <groupId>com.foxinmy</groupId>
  <artifactId>weixin4j-mp</artifactId>
  <version>RELEASE</version>
</dependency>
  • 配置weixin4j.properties檔案
# weixin4j的配置檔案:如果沒有請構造相應引數傳入 如果有請保證在classpath的根目錄下

# 公眾號資訊 請按需填寫
weixin4j.account={"id":"公眾號APPID","secret":"公眾號APPsecret",\ "components":[{"id":"應用元件的id","secret":"應用元件的secret"}],\ "mchId":"商戶ID",\ "certificateKey":"預設商戶ID",\ "certificateFile":"classpath:apiclient_cert.p12//退款的證書檔案路徑",\ "paySignKey":"支付金鑰"}
  • 在sping的配置檔案中配置weixin4j的核心API
<!-- 注入weixin4j核心類,並使用redis管理token -->
<bean id="weixinProxy" class="com.foxinmy.weixin4j.mp.WeixinProxy"> <constructor-arg> <bean class="com.foxinmy.weixin4j.cache.RedisCacheStorager" /> </constructor-arg> </bean> <!-- 微信支付介面代理 start --> <bean id="weixinPayProxy" class="com.foxinmy.weixin4j.payment.WeixinPayProxy"
/>
<!-- 微信支付介面代理 end -->
  • 介面實現
package net.seedor.controller.wechat;

import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.OauthApi;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import net.seedor.pojo.User;
import net.seedor.pojo.vo.UserVO;
import net.seedor.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * Date: 2018/3/30
 * Author: Zp.Xiao
 * 微信登入
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/login")
public class LoginController {

    private final String REDIRECTURL = "授權成功回撥URL";

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WeixinProxy weixinProxy;

    @Autowired
    private UserService userService;

    /**
     * 微信授權登入
     * @param: state 前端頁面的URL
     */
    @RequestMapping(value = "/userLogin" , method = RequestMethod.GET)
    public ResponseEntity<ExecuteResult> userLogin(@RequestParam(name = "state") String state, HttpServletResponse response) {
        ExecuteResult<Object> result = new ExecuteResult<>();
        try {
            OauthApi oauthApi = weixinProxy.getOauthApi();
            String userAuthorizationURL = oauthApi.getUserAuthorizationURL(REDIRECTURL, state, "snsapi_userinfo");
            response.sendRedirect(userAuthorizationURL);
        } catch (Exception e) {
            e.printStackTrace();
            ExecuteResultUtil.setErrorResult(result,"接入登入失敗");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 授權成功回掉函式
     * @param: 授權成功返回的code
     * @param: homeUrl 前端傳遞的URL
     * @return user
     */
    @RequestMapping("/getUserInfo")
    public ResponseEntity<ExecuteResult> userAuthenticator(@RequestParam(name = "code") String code , HttpServletResponse response ,
                                                           @RequestParam(name = "state") String homeUrl) {
        ExecuteResult<Object> result = new ExecuteResult<>();
        OauthApi oauthApi = weixinProxy.getOauthApi();
        OauthToken oauthToken = null;
        try {
            UserVO userVO = userService.insertUser(code, oauthApi);
            //重定向到前端頁面,並將token拼接到URL中
            response.sendRedirect(homeUrl + "?token=" + userVO.getToken());
        } catch (Exception e) {
            e.printStackTrace();
            ExecuteResultUtil.setErrorResult(result,"接入登入失敗");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 通過token獲取使用者資訊介面
     */
    @RequestMapping(value = "/checkUserLogin" , method = RequestMethod.POST)
    public ResponseEntity<ExecuteResult> checkUserLogin(@RequestParam("token")String userToken) {
        ExecuteResult<Object> result = new ExecuteResult<>();
        try {
            if(StringUtils.isNotBlank(userToken)) {
                result.setData(userService.queryUserForRedis(userToken));
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ExecuteResultUtil.setErrorResult(result,"當前沒有使用者登入");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
        return ResponseEntity.ok(result);
    }
}

前端判斷當前頁面url中是否有token,如果有,調根據token獲取使用者資訊介面,如果沒有,請求微信登入介面。

  • service
package net.seedor.service.impl;

import com.foxinmy.weixin4j.mp.api.OauthApi;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import net.seedor.pojo.vo.UserVO;
import net.seedor.utils.EntityUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.seedor.common.service.redis.RedisService;
import net.seedor.pojo.User;
import java.util.UUID;

/**
 * Date: 2018/3/30
 * Author: Zp.Xiao
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisService redisService;

    @Override
    public UserVO insertUser(String code, OauthApi oauthApi) throws Exception {
        OauthToken oauthToken = oauthApi.getAuthorizationToken(code);//通過code獲取使用者的token
        com.foxinmy.weixin4j.mp.model.User userInfo = oauthApi.getAuthorizationUser(oauthToken);    //通過token獲取使用者資訊
        //將使用者資訊儲存到資料庫
        //UUID生成token
        //key為token,value為使用者頭像暱稱,儲存到redis
        return userVO;
    }
}

ResponseEntity只是一個封裝資料的類。
UserVO 中儲存了使用者標識的token與常用的資料。