spring boot写的微信小程序登录授权

Controller层 :

package com.searchmarket.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: SearchMarket
 * @description: 微信授权接口
 * @Author: 小白白
 * @create: 2020/02/20 - 22:43
 **/
@RequestMapping("wx")
@RestController
public class WeiXinController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("login")
    public Map<String, Object> wxLogin(@RequestParam("code")String code){
        Map<String, Object> result = new HashMap<>();
        result.put("status",200);

        String appid = "wx111111111111111f0e6";
        String secret = "11111111111111111111111111111";
        String url =    "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                        "&secret="  + secret +
                        "&js_code=" + code   +
                        "&grant_type=authorization_code";
        String jsonData = this.restTemplate.getForObject(url,String.class);
        if (StringUtils.contains(jsonData,"errcode")){
            //校验出错
            result.put("status",500);
            result.put("msg","登录失败");
            return  result;
        }
        String md5Key = DigestUtils.md5Hex(jsonData + "SM_WX_LOGIN");

        String redisKey = "SM_LOGIN_" + md5Key;

        //规则:WX_LOGIN——
        this.redisTemplate.opsForValue().set(redisKey,jsonData, Duration.ofDays(30));
        result.put("ticket","SM_" + md5Key);

        return result;
    }
}

Config基础配置类

package com.searchmarket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @program: SearchMarket
 * @description: redis工具类
 * @Author: 小白白
 * @create: 2020/02/20 - 22:54
 **/
@Configuration
public class SM_Config {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

你可能感兴趣的:(Demo,java)