最近對接開發(fā)微信小程序,需要獲取用戶的openid使用支付,所以記下這篇通用小程序授權筆記。
這里使用到開源工具Wx-Java
此致 致敬?binarywang 大佬?
maven引入如下
<!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-miniapp -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.3.3.B</version>
</dependency>
準備參數(shù),application配置文件需配置參數(shù)
wx:
miniapp:
appid: 微信官方申請的appid
secret: 微信官方申請的秘鑰
msgDataFormat: JSON #數(shù)據(jù)可以,默認json就ok
編寫WxMaProperties.java文件獲取配置文件中的字段
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
/**
* 設置微信小程序的appid
*/
private String appid;
/**
* 設置微信小程序的Secret
*/
private String secret;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}
創(chuàng)建配置類WxMaConfiguration配置初始化配置
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
@Bean
public WxMaService wxMaService(WxMaProperties properties) {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(properties.getAppid());
config.setSecret(properties.getSecret());
config.setMsgDataFormat(properties.getMsgDataFormat());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}
controller編寫授權代碼
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "微信模塊")
@RestController
@RequestMapping("/wx/auth")
@RequiredArgsConstructor
public class WxController extends BaseController {
private final WxMaService wxService;
@ApiOperation("微信登陸")
@GetMapping(value = "/getWxInfo", produces = "application/json")
@SneakyThrows(WxErrorException.class)
public WxMaJscode2SessionResult getWxInfo(@ApiParam("小程序CODE") String code){
WxMaJscode2SessionResult wx = wxService.jsCode2SessionInfo(code);
logger.info("請求微信授權完成=>{}",wx);
return wx;
}
}
非常簡單,倆行代碼直接搞定授權。文章來源:http://www.zghlxwxcb.cn/news/detail-592250.html
覺得有用的話記得給個贊,謝謝各位大佬了。?文章來源地址http://www.zghlxwxcb.cn/news/detail-592250.html
到了這里,關于Java開發(fā)微信小程序授權登錄的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!