111
wang-hao-jie
2022-08-25 d90da0759bd93c7f429f6a20bc835782ad927c02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.boying.controller.phone;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boying.common.BaseController;
import com.boying.common.util.HttpUtil;
import com.boying.common.util.StringUtil;
import com.boying.entity.User;
import com.boying.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.List;
 
@RestController
@RequestMapping("wx")
public class WxLogin extends BaseController {
 
    @Autowired
    private UserService userService;
 
    @RequestMapping("/login")
    public Object doLogin(String code){
 
        JSONObject SessionKeyOpenId = getSessionKeyOrOpenId( code );
 
        String openid = SessionKeyOpenId.getString("openid" );
 
        //String sessionKey = SessionKeyOpenId.getString( "session_key" );
        if(StringUtil.isNullOrEmpty(openid)){
            return error(SessionKeyOpenId.toJSONString());
        }
        List<User> l = userService.findAll("openid",openid);
        User user = null;
        if(l.size()>0){
            user = l.get(0);
        }
        if(user==null){
            return error("请注册账户",openid);
        }else {
            return success("登录成功",user);
        }
    }
 
    public static JSONObject getSessionKeyOrOpenId(String code){
        //微信端登录code
        String wxCode = code;
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=wx0f10f6d253f3ee6b&secret=4d4cbc8da31a96559114ad693de70631&grant_type=authorization_code&js_code="+code;
//        Map<String,String> requestUrlParam = new HashMap<String, String>(  );
//        requestUrlParam.put( "appid","wx940911bf60031451" );//小程序appId
//        requestUrlParam.put( "secret","6685bef68f87823f048f2a6cb7c12dc9" );
//        requestUrlParam.put( "js_code",wxCode );//小程序端返回的code
//        requestUrlParam.put( "grant_type","authorization_code" );//默认参数
 
        //发送post请求读取调用微信接口获取openid用户唯一标识
        //JSONObject jsonObject = JSON.parseObject( HttpUtil.jsonPost2(JSON.toJSONString(requestUrlParam),requestUrl ));
        JSONObject jsonObject = JSON.parseObject( HttpUtil.get(requestUrl));
        return jsonObject;
    }
}