开发网页微信登入获取微信用户信息

(48) 2024-02-23 18:01:01

1、先进入微信公众号测试平台(填写这些的时候需要买域名,我买的是阿里云域名):

微信公众平台

用自己微信登入可以获取自己的appid和appsecret

2、在idea后台写代码,此处的token就是测试平台自己设置的token:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@RestController
@RequestMapping("/wx")
public class WxTestController {

    private Logger log = LoggerFactory.getLogger(WxTestController.class);

    private String TOKEN = "*****";

    @RequestMapping("/login")
    public String login(@RequestParam("signature") String signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce,
                        @RequestParam("echostr") String echostr) {
        log.info("timestamp:"+timestamp);
        log.info("nonce:"+nonce);
        //排序
        String sortString = sort(TOKEN, timestamp, nonce);
        //加密
        String myString = sha1(sortString);
        //校验
        if (myString != null && myString != "" && myString.equals(signature)) {
            System.out.println("签名校验通过");
            //如果检验成功原样返回echostr,微信服务器接收到此输出,才会确认检验完成。
            return echostr;
        } else {
            System.out.println("签名校验失败");
            return "";
        }
    }

    public String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);
        StringBuilder sb = new StringBuilder();
        for (String str : strArray) {
            sb.append(str);
        }

        return sb.toString();
    }

    public String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}

3、二级域名在那个js框中,-----不带http://!!!!

4、代码上传服务器启动项目,然后点击提交,提示连接成功便完成。

接下来就是需要登入获取用户信息了

一共就四步,附上 微信开发文档连接:网页授权 | 微信开放文档

1 第一步:用户同意授权,获取code

2 第二步:通过code换取网页授权access_token

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

5 附:检验授权凭证(access_token)是否有效

代码如下:

mport com.naruto.huo.util.AuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class WxLoginController{

    private Logger log = LoggerFactory.getLogger(WxLoginController.class);

    /**
     *
     */

    private static final long serialVersionUID = 1L;

    @RequestMapping("/wxLogin")
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        log.info("进入WxLoginController");
        //第一步:引导用户进入授权页面同意授权,获取code
        //回调地址
        String backUrl = "*****";         //第1种情况使用

       // String backUrl = "*****k";//第2种情况使用,这里是web.xml中的路径


        //授权页面地址

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID

                + "&redirect_uri=" + URLEncoder.encode(backUrl)

                + "&response_type=code"

                + "&scope=snsapi_userinfo"

                + "&state=STATE#wechat_redirect";


        //重定向到授权页面

        response.sendRedirect(url);

    }

}

import com.naruto.huo.model.UserVx;
import com.naruto.huo.util.AuthUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.Date;

@Controller
public class WxIndexController {

    /**
     *
     */
    private Logger log = LoggerFactory.getLogger(WxIndexController.class);

    private static final long serialVersionUID = 1L;

    //1. 获取JDBCTemplate对象
    @Autowired
    private JdbcTemplate jdbcTemplate;


    private String dbUrl;

    private String driverClassName;

    private String userName;

    private String passWord;


    private Connection conn = null;

    private PreparedStatement ps = null;

    private ResultSet rs = null;


    //初始化数据库
    public void init(ServletConfig config) throws ServletException {


        //加载驱动

        try {

            this.dbUrl = config.getInitParameter("dbUrl");

            this.driverClassName = config.getInitParameter("driverClassName");

            this.userName = config.getInitParameter("userName");

            this.passWord = config.getInitParameter("passWord");

            Class.forName(driverClassName);

        } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    @RequestMapping("/callBack")
    protected ModelAndView callBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        log.info("进入获取code后台");
        //第二步:通过code换取网页授权access_token


        //从request里面获取code参数(当微信服务器访问回调地址的时候,会把code参数传递过来)

        String code = request.getParameter("code");


        System.out.println("code:" + code);


        //获取code后,请求以下链接获取access_token

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID

                + "&secret=" + AuthUtil.APPSECRET

                + "&code=" + code

                + "&grant_type=authorization_code";


        //通过网络请求方法来请求上面这个接口

        JSONObject jsonObject = AuthUtil.doGetJson(url);


        System.out.println("==========================jsonObject" + jsonObject);


        //从返回的JSON数据中取出access_token和openid,拉取用户信息时用

        String token = jsonObject.getString("access_token");
        System.out.println("第一次的token:"+token);
        String openid = jsonObject.getString("openid");
        String refresh_token = jsonObject.getString("refresh_token");

        // 第三步:刷新access_token(如果需要)
        JSONObject jsonObjectRefresh = AuthUtil.getRefreshToken(refresh_token);
        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        System.out.println("==========================jsonObjectRefresh" + jsonObjectRefresh);
        String tokenR = jsonObject.getString("access_token");
        String openidR = jsonObject.getString("openid");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenR
                + "&openid=" + openidR
                + "&lang=zh_CN";

        //通过网络请求方法来请求上面这个接口

        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

        //存储此用户
        UserVx userVx = new UserVx();
        userVx.setOpenId((String)userInfo.get("openid"));
        userVx.setPassword("123456");
        userVx.setUpdateTime(new Date());
        userVx.setCreateTime(new Date());
        log.info("获取到openid:"+(String)userInfo.get("openid"));
        Integer count = jdbcTemplate.queryForObject("select count(1) from user_wx where openid = ?",Integer.class,new Object[]{(String)userInfo.get("openid")});
        log.info("此用户存在几个:"+count);
        if(count == 0){
            String sql = "insert into user_wx (openid,password,create_time,update_time) values (?,?,?,?)";
            jdbcTemplate.update(sql,(String)userInfo.get("openid"),"123456",new Date(),new Date());
            log.info("插入一条数据成功");
        }else{
            String sql = "update user_wx update_time = ? where openid = ?";
            jdbcTemplate.update(sql,new Date(),(String)userInfo.get("openid"));
        }

        //第1种情况:使用微信用户信息直接登录,无需注册和绑定

        request.setAttribute("info", userInfo);
        //直接跳转
//        request.getRequestDispatcher("/index1Wx.html").forward(request, response);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index1Wx");
        return  mv;
        //第2种情况: 将微信与当前系统的账号进行绑定(需将第1种情况和@WebServlet("/callBack")注释掉)

        //第一步,根据当前openid查询数据库,看是否该账号已经进行绑定

   /*     try {

            String nickname = getNickName(openid);

            if (!"".equals(nickname)) {

                //已绑定

                request.setAttribute("nickname", nickname);

                request.getRequestDispatcher("/indexWx2.html").forward(request, response);

            } else {

                //未绑定

                request.setAttribute("openid", openid);

                request.getRequestDispatcher("/loginWx.html").forward(request, response);

            }

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }*/


    }


    //数据库的查询

    public String getNickName(String openid) throws SQLException {

        String nickName = "";

        //创建数据库链接

        conn = DriverManager.getConnection(dbUrl, userName, passWord);

        String sql = "select nickname from user where openid = ?";

        ps = conn.prepareStatement(sql);

        ps.setString(1, openid);

        rs = ps.executeQuery();

        while (rs.next()) {

            nickName = rs.getString("nickname");

        }


        //关闭链接

        rs.close();

        ps.close();

        conn.close();


        return nickName;

    }


    //数据库的修改(openid的綁定)

    public int updateUser(String account, String password, String openid) throws SQLException {


        //创建数据库链接

        conn = DriverManager.getConnection(dbUrl, userName, passWord);

        String sql = "update user set openid = ? where account = ? and password = ?";

        ps = conn.prepareStatement(sql);

        ps.setString(1, openid);

        ps.setString(2, account);

        ps.setString(3, password);

        int temp = ps.executeUpdate();


        //关闭链接

        rs.close();

        ps.close();

        conn.close();


        return temp;

    }
/*

    //post方法,用来接受登录请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String account = request.getParameter("account");

        String password = request.getParameter("password");

        String openid = request.getParameter("openid");


        try {

            int temp = updateUser(account, password, openid);


            if (temp > 0) {

                String nickname = getNickName(openid);

                request.setAttribute("nickname", nickname);

                request.getRequestDispatcher("/indexWx2.html").forward(request, response);

                System.out.println("账号绑定成功");

            } else {

                System.out.println("账号绑定失败");

            }


        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }


    }*/


}

成功后:扫码即可获取信息开发网页微信登入获取微信用户信息 (https://mushiming.com/)  第1张

THE END

发表回复