微信公众号网页授权开发

1、配置公众号信息

2、spring-boot yml配置

server:
  port: 80 #端口由脚本配置


## 微信公众号授权
wx:
  mp:
    app-id: APPID
    secret: SECRET
    token: token123456
    config-storage:
      http-client-type: httpclient

3、pom配置

<!-- 微信公众号包 -->
		<dependency>
		  <groupId>com.github.binarywang</groupId>
		  <artifactId>wx-java-mp-spring-boot-starter</artifactId>
		  <version>3.9.0</version>
		</dependency>
		
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-web</artifactId>
	    </dependency>
	    
	    <dependency>
	    	<groupId>org.springframework.boot</groupId>
	    	<artifactId>spring-boot-starter-thymeleaf</artifactId>
	    </dependency>
	    
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

		<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpclient</artifactId>
	    </dependency>

4、代码结构

5、账号配置

package com.hollycrm.oatm.ams.wx.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 微信公众号账号信息配置
 * 
 * @author Administrator
 *
 */
@Configuration
@ConfigurationProperties(prefix = "wx.mp")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AccountConfig {
	private String appId;
	private String secret;
	private String token;
}

6、微信bean相关配置

package com.hollycrm.oatm.ams.wx.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxOAuth2Service;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxOAuth2ServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;

/**
 * 微信公众号三方包bean配置
 * 
 * @author admin
 *
 */
@Configuration
public class WxConfig {
	@Autowired
    private AccountConfig accountConfig;

    @Bean
    public WxMpConfigStorage wxMpConfigStorage(){
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(accountConfig.getAppId());
        config.setSecret(accountConfig.getSecret());
        return config;
    }

    @Bean
    public WxMpService wxMpService(){
        WxMpServiceImpl service = new WxMpServiceImpl();
        service.setWxMpConfigStorage(wxMpConfigStorage());
        return service;
    }
    
    @Bean
    public WxOAuth2Service wxOAuth2Service(){
        WxOAuth2ServiceImpl auth2Service = new WxOAuth2ServiceImpl(wxMpService());
        return auth2Service;
    }
}

7、授权功能

package com.hollycrm.oatm.ams.wx.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxOAuth2Service;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信网页授权功能
 * 
 * @author admin
 *
 */
@Controller
public class WxAuthController {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	WxOAuth2Service wxOAuth2Service;
	
	/**
	 * 最终跳转的界面
	 * @return
	 */
	@GetMapping("/index")
	public String index() {
		return "index";
	}
	
	/**
	 * 授权接口
	 * @param url 
	 * @return
	 */
	@GetMapping("/authorize")
	public String authorize(String url) {
		String redirectUrl = "http://c9dc97501942.ngrok.io/hollycrm-oatm-ams/userInfo";
		String authorizationUrl = wxOAuth2Service.buildAuthorizationUrl(redirectUrl,
				WxConsts.OAuth2Scope.SNSAPI_USERINFO, url);
		log.info("authorizationUrl:{}", authorizationUrl);
		return "redirect:" + authorizationUrl;
	}
	
	/**
	 * 重定向接口:静默拉取用户信息
	 * 
	 * @param code
	 * @param state
	 * @return
	 */
	@GetMapping("/userInfo")
	public String userInfo(RedirectAttributes redirectAttributes,@RequestParam("code") String code, @RequestParam("state") String state) {
		log.info("code:{}", code);
		log.info("state:{}", state);
		WxMpOAuth2AccessToken token;
		try {
			token = wxOAuth2Service.getAccessToken(code);
			String openId = token.getOpenId();// 用户openID
			log.info("openId:{}", openId);
			WxMpUser user = wxOAuth2Service.getUserInfo(token, "zh_CN");
			log.info("user:{}", user);
			redirectAttributes.addFlashAttribute("user", user);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return "redirect:" + state;
	}
}

8、调整界面

<!DOCTYPE html>
<html  xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>抽奖界面...</title>
</head>
<body>
	<h1>抽奖界面...</h1>
	<h1>用户信息:</h1>
	<div>
		姓名:<span th:text="${user.nickname}"></span><br/>
		性别:<span th:text="${user.sexDesc}"></span><br/>
		图像:<img th:src="${user.headImgUrl}"></img>
	</div>
</body>
</html>

9、演示效果

访问授权接口: http://c9dc97501942.ngrok.io/hollycrm-oatm-ams/authorize?url=%22http://c9dc97501942.ngrok.io/hollycrm-oatm-ams/index%22

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值