0
点赞
收藏
分享

微信扫一扫

小程序后台数据交互-个人中心

司马吹风 2023-01-05 阅读 133

目录

一,获取用户昵称和头像

登录过程

二,登录-小程序

三,后台

小程序服器配置


一,获取用户昵称和头像

登录过程

小程序登录

小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。

二,登录-小程序

login.js

user.loginByWeixin(res.userInfo).then(res => {
    app.globalData.hasLogin = true;
    wx.navigateBack({
    delta: 1
    })
})

user.js

function loginByWeixin(userInfo) {
  return new Promise(function(resolve, reject) {
    return login().then((res) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, {
        code: res.code,
        userInfo: userInfo
      }, 'POST').then(res => {
        if (res.errno === 0) {
          //存储用户信息
          wx.setStorageSync('userInfo', res.data.userInfo);
          wx.setStorageSync('token', res.data.token);
          resolve(res);
        } else {
          reject(res);
        }
      })

util.js

function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      timeout:6000,
      header: {
        'Content-Type': 'application/json',
        'X-OA-Token': wx.getStorageSync('token')
      },

emoji

三,后台

小程序服器配置

导入微信小程序SDK

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-miniapp</artifactId>
    <version>3.3.0</version>
</dependency>

application.yml

oa:
  wx:
    app-id: wxf23b28b5e4ea4d6a
    app-secret: 212621faa31cdf0691367ea45b2b6041
    msgDataFormat: JSON

WxProperties

封装oa.wx的数据

@Data
@Configuration
@ConfigurationProperties(prefix = "oa.wx")
public class WxProperties {
	/**
	 * 设置微信小程序的appId
	 */
	private String appId;
	/**
	 * 设置微信小程序的Secret
	 */
	private String appSecret;
	/**
	 * 消息数据格式
	 */
	private String msgDataFormat;

}

WxConfig

注册WxMaService

@Configuration
public class WxConfig {
	@Autowired
	private WxProperties properties;

	@Bean
	public WxMaConfig wxMaConfig() {
		WxMaInMemoryConfig config = new WxMaInMemoryConfig();
		config.setAppid(properties.getAppId());
		config.setSecret(properties.getAppSecret());
		config.setMsgDataFormat(properties.getMsgDataFormat());
		return config;
	}

	@Bean
	public WxMaService wxMaService(WxMaConfig maConfig) {
		WxMaService service = new WxMaServiceImpl();
		service.setWxMaConfig(maConfig);
		return service;
	}

}

WxAuthController

@RequestMapping("/wx/auth")
public class WxAuthController {
    @Autowired
    private WxMaService wxService;
     @PostMapping("login_by_weixin")
    public Object loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {

        //客户端需携带code与userInfo信息
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return ResponseUtil.badArgument();
        }
        //调用微信sdk获取openId及sessionKey
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();//session id
            openId = result.getOpenid();//用户唯一标识 OpenID
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            log.error("微信登录,调用官方接口失败:{}", code);
            return ResponseUtil.fail();
        }else{
            log.info("openId={},sessionKey={}",openId,sessionKey);
        }
        //根据openId查询wx_user表
        //如果不存在,初始化wx_user,并保存到数据库中
        //如果存在,更新最后登录时间
        //....
        // token
        UserToken userToken = null;
        try {
            userToken = UserTokenManager.generateToken(user.getId());
        } catch (Exception e) {
            log.error("微信登录失败,生成token失败:{}", user.getId());
            e.printStackTrace();
            return ResponseUtil.fail();
        }
        userToken.setSessionKey(sessionKey);
        log.info("SessionKey={}",UserTokenManager.getSessionKey(user.getId()));
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", userToken.getToken());
        result.put("tokenExpire", userToken.getExpireTime().toString());
        result.put("userInfo", userInfo);
        //....


        log.info("【请求结束】微信登录,响应结果:{}", JSONObject.toJSONString(result));

        return ResponseUtil.ok(result);
    }

响应给客户端数据有:token userInfo

举报

相关推荐

0 条评论