<!-- 微信小程序,工具包 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.2.0</version>
</dependency>
# 微信小程序配置(注册小程序账号获取)
wx:
miniapp:
appId: xxxxxxx
secret: xxxxxxxx
@Data
@Configuration
@ConditionalOnClass(WxMaService.class)
@ConfigurationProperties(prefix ="wx.miniapp")
public class WxMaConfiguration {
private String appId;
private String secret;
@Bean
@ConditionalOnMissingBean(WxMaService.class)
public WxMaService wxMaService() {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(this.getAppId());
config.setSecret(this.getSecret());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}
@Slf4j
@Component
public class WxUtil {
@Autowired
private AlarmService alarmService; //业务类,用于保存小程序用户的openid
@Autowired
WxMaService wxMaService;
public void saveOpenId(Long userId, String jsCode) {
try {
WxMaJscode2SessionResult code2SessionInfo = wxMaService.jsCode2SessionInfo(jsCode);
if (code2SessionInfo != null) {
alarmService.addWechatLoginInfo(userId, code2SessionInfo.getOpenid(),
code2SessionInfo.getSessionKey(), LocalDateTime.now());
}
} catch (Exception e) {
log.error("保存微信登录信息发生错误错误~ [userId=" + userId + ", jsCode=" + jsCode, e);
}
}
}
/**
* 微信用户登录对象
*
* @author ruoyi
*/
public class WxLoginBody
{
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String password;
/**
* 微信code
*/
private String jsCode;
// set get方法略
}
/**
* 小程序登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@ApiOperation("用户登录")
@PostMapping("/wx/login")
public AjaxResult wxLogin(@RequestBody WxLoginBody loginBody)
{
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getJsCode());
ajax.put(Constants.TOKEN, token);
return ajax;
}
login() {
uni.login({
provider: 'weixin',
success: function (loginRes) {
/* loginRes.code 用户登录凭证(有效期五分钟)code
* 使用 code 换取 openid、unionid、session_key 等信息示例代码
* 参考微信帮助文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
*/
uni.request({
url: 'http://xxxxx/wx/login', //服务端地址
method:"POST",
data: {
"username": "用户名",
"password": "密码",
"jsCode": loginRes.code
},
header: {
'custom-header': 'hello' //自定义请求头信息
},
success: (res) => {
console.log(res);
}
});
}
})
}
后续持续更新。。。