密通学院

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 4725|回复: 0

微信登录的几种方式

[复制链接]
  • TA的每日心情
    可爱
    2018-6-29 10:04
  • 289

    主题

    319

    帖子

    9万

    铜板

    超级版主

    Rank: 8Rank: 8

    积分
    93815
    QQ
    发表于 2019-3-14 10:11:30 | 显示全部楼层 |阅读模式

    马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

    您需要 登录 才可以下载或查看,没有帐号?立即注册

    x
    微信登录分为两类:需要用户确认的授权登录与静默授权,用户确认的授权登录因为要通过用户的个人确认,所以可以获取用户全面的信息,无论是否关注相关微信号都可以获取,静默授权是嵌套在普通网页中的授权方式,不需要用户确认,但只能获取微信用户的唯一标识openid,但有时候这种交互方式更加的友好,对于用户的简单认证还是很有用的。

    1、授权登录需要拉起需要用户确认的授权页(`・ω・′)

    有些人可能会不喜欢,例如我老板(T_T),此方式可以获取比较多的信息,例如头像、昵称、openid、unionid、是否关注公众号等信息
    个人认为此种授权方式比较适合纯在微信端运营的网站,如果不考虑脱离微信端的话。
    2、静默登录,这个当前环境下很流行,用appid去获取code然后获取用户的openid,拿到openid之后就可以进行自己业务处理了,从体验上来说用户无感,没有上面那个授权页,个人认为此种授权方式比较适合较为独立或者正在考虑脱离微信的网站,
    3、扫码登录,此种方式一般适用于电商网站的PC登录,如下图

    好啦,开始介绍开发流程。
    1、授权登录:
    a)、首先需要在公众号取得相应的获取用户基本信息的权限。推荐适用拦截器的方式拦截部分需要授权的功能,例如钱包、个人中心等,对于网站介绍,或者一些推广页、首页这些不需要授权可以提升一下用户体验,虽然从开发的角度看意义不大,拦截代码如下
    1. package com.xxx.filter;

    2. import com.xxx.util.CookieUtil;
    3. import com.xxx.util.IPUtil;
    4. import org.apache.commons.lang.StringUtils;
    5. import org.slf4j.Logger;
    6. import org.slf4j.LoggerFactory;

    7. import javax.servlet.*;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;

    11. public class WeChatUserFilter implements Filter {

    12.     protected static final Logger LOG = LoggerFactory.getLogger(WeChatUserFilter.class);

    13.     @Override
    14.     public void destroy() {
    15.     }

    16.     @Override
    17.     public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain)
    18.             throws IOException, ServletException {
    19.         HttpServletRequest request = (HttpServletRequest) _request;
    20.         HttpServletResponse response = (HttpServletResponse) _response;
    21.         // 获取当前访问路径
    22.         String path = request.getRequestURI().toString();
    23.         // 拦截地址配置
    24.         String[] filterUrls = { "/home", "/XXXX/XXX", "/XXX/XXXX" };
    25.         for (String url : filterUrls) {
    26.             if (path.contains(url)) {
    27.                 // 拦截
    28.                 LOG.info("拦截的地址是:" + path + ",ip:" + IPUtil.getIpAddr(request));
    29.                 String openid = CookieUtil.getCookieValue(request, "openid");
    30.                 if (StringUtils.isNotBlank(openid)) {
    31.                     chain.doFilter(_request, _response);
    32.                     return;
    33.                 }
    34.                 if (StringUtils.isNotBlank(request.getQueryString())) {
    35.                     path += "?" + request.getQueryString();
    36.                 }
    37.                 response.sendRedirect(response.encodeURL("/user/login?u=" + response.encodeURL(path)));
    38.                 return;
    39.             }
    40.         }
    41.         chain.doFilter(_request, _response);
    42.     }

    43.     @Override
    44.     public void init(FilterConfig arg0) throws ServletException {
    45.         // TODO Auto-generated method stub

    46.     }

    47. }
    复制代码

    b)、如果用户没有进行过授权则会跳转到/user/login中进行登录,完整的登录代码如下
    1. @RestController
    2. @RequestMapping(value = "user")
    3. public class LoginController {
    4.     protected static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    5.     // 公众号APPID
    6.     public static final String WX_APPID = "XXXXXXXXXXXX";
    7.     // 公众号SECRET
    8.     public static final String WX_APP_SECRET = "XXXXXXXXXXXX";

    9.     @RequestMapping(value = "login", method = RequestMethod.GET)
    10.     public void toLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
    11.         // 获取cookie中的openid
    12.         String openid = CookieUtil.getCookieValue(request, "openid");
    13.         String unionid = CookieUtil.getCookieValue(request, "unionid");
    14.         // 定义微信授权之后的跳转地址命名方式为(http://你的网址+/user/login?u=)
    15.         String reUrl = "";
    16.         // 获取需要跳转的url
    17.         String u = request.getParameter("u");
    18.         LOG.error("需要跳转的url为:", u);
    19.         // 判断如果openid不存在,则获取code
    20.         // 如果拦截到的跳转的地址为空则给个默认值
    21.         if (StringUtils.isBlank(u)) {
    22.             u = "/indexController/index";
    23.         }
    24.         if (StringUtils.isBlank(openid) || StringUtils.isBlank(unionid)) {
    25.             // 获取code
    26.             String code = request.getParameter("code");
    27.             LOG.error("code:", code);
    28.             if (StringUtils.isBlank(code)) {
    29.                 // 跳转到微信端获取code
    30.                 String redrictUrl = response.encodeURL(reUrl + response.encodeURL(u));
    31.                 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WX_APPID + "&redirect_uri="
    32.                         + redrictUrl + "&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
    33.                 try {
    34.                     response.sendRedirect(url);
    35.                 } catch (IOException e) {
    36.                     // logger.error("url:重定向错误");
    37.                 }
    38.                 return;
    39.             } else {
    40.                 // 获取用户信息
    41.                 JSONObject object = getSnsapiUserinfo(request, code);
    42.                 if (object != null) {
    43.                     String user_unionid = object.getString("unionid");
    44.                     String user_openid = object.getString("openid");
    45.                     if (StringUtils.isBlank(user_unionid) || StringUtils.isBlank(user_openid)) {
    46.                         return;
    47.                     }
    48.                     String headimgurl = object.getString("headimgurl");
    49.                     String nickname = EmojiFilter.filterEmoji(object.getString("nickname"));
    50.                 }

    51.             }
    52.         }
    53.         // 返回客户访问页面
    54.         try {
    55.             response.sendRedirect(u);
    56.         } catch (IOException e) {
    57.             // logger.error("url:重定向错误");
    58.         }
    59.     }

    60.     public static JSONObject getSnsapiUserinfo(HttpServletRequest request, String code)
    61.             throws org.apache.commons.httpclient.HttpException {
    62.         JSONObject wxuser;

    63.         String t_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret="
    64.                 + WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
    65.         Proxy httproxy = new Proxy();
    66.         final String result = httproxy.get(t_url, null);
    67.         LOG.info("sns/oauth2/access_token:" + result);
    68.         JSONObject obj = JSON.parseObject(result);
    69.         String openid = obj.getString("openid");
    70.         // 判断用户是否存在
    71.         String t_access_token = obj.getString("access_token");
    72.         String t_url_2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + t_access_token + "&openid=" + openid;
    73.         final String res2 = httproxy.get(t_url_2, null);
    74.         wxuser = JSON.parseObject(res2);
    75.         LOG.info("网页授权获取用户基本信息:" + wxuser.toString());
    76.         return wxuser;
    77.     }
    78. }
    复制代码

    2、静默登录 静默登录只需在授权登录的基础之上更改scope参数的值即可 如下
    1. String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WX_APPID + "&redirect_uri="                        + redrictUrl + "&response_type=code&scope=     snsapi_base&state=0#wechat_redirect";
    复制代码

    3、扫码登录就简单很多了
    只需拉起微信扫码页然后设置扫码成功之后的回调方法即可,具体如下:
    a)、拉起微信扫码登录页
    1. String WX_SCAN_CODE_URL = "https://open.weixin.qq.com/connect/qrconnect?appid={APPID}&redirect_uri={REUTL}&response_type=code&scope=snsapi_login&state={STATE}#wechat_redirect";
    2.     // 千万要记住,这个是微信开放平台的APPID
    3.     String WX_PLATFROM_APPID = "XXXXXX";
    4.     // 你的回调地址
    5.     String scanReUrl = "http://你的网址/user/wxLoginCallback";

    6.     /**
    7.      * 微信扫码登陆
    8.      *
    9.      * @param request
    10.      * @param response
    11.      */
    12.     @RequestMapping(value = "weixinScanLogin", method = RequestMethod.GET)
    13.     public void weixinRetrun(HttpServletRequest request, HttpServletResponse response) throws Exception {
    14.         // 获取回调url(非必填,只是附带上你扫码之前要进入的网址,具体看业务是否需要)
    15.         String url = request.getParameter("reurl");
    16.         // 拼接扫码登录url
    17.         String wxLoginurl = WX_SCAN_CODE_URL;
    18.         wxLoginurl = wxLoginurl.replace("{APPID}", WX_PLATFROM_APPID).replace("{REUTL}", scanReUrl).replace("{STATE}",
    19.                 url);
    20.         wxLoginurl = response.encodeURL(wxLoginurl);
    21.         response.sendRedirect(wxLoginurl);
    22.     }
    复制代码

    b)、微信扫码登录的回调地址
    1. // 千万要记住,这个是微信开放平台的APPID
    2.     String WX_PLATFROM_APPID = "XXXXXXXXX";
    3.     // 千万要记住,这个是微信开放平台的APPSECRET
    4.     String WX_PLATFORM_APPSECRET = "XXXXXXXXXX";
    5.     // 拉起微信扫码页地址
    6.     String WX_SCAN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    7.     // 微信扫码之后获取用户基本信息的地址
    8.     String WX_SCAN_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    9.     /**
    10.      * 微信扫码登录回调
    11.      *
    12.      * @param request
    13.      * @param response
    14.      * @return
    15.      * @throws Exception
    16.      */
    17.     @RequestMapping(value = "wxLoginCallback", method = RequestMethod.GET)
    18.     public void loginCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
    19.         String code = request.getParameter("code");
    20.         if (code == null) {
    21.             // 用户禁止授权
    22.         }
    23.         String url = WX_SCAN_URL.replace("APPID", WX_PLATFROM_APPID).replace("SECRET", WX_PLATFORM_APPSECRET)
    24.                 .replaceAll("CODE", code);
    25.         url = response.encodeURL(url);
    26.         try {
    27.             String result = HttpClientUtils.get(url, null);
    28.             Map<String, Object> resultMap = JsonHelper.toMap(result);
    29.             String unionid = (String) resultMap.get("unionid");
    30.             String access_token = (String) resultMap.get("access_token");
    31.             String openid = (String) resultMap.get("openid");
    32.             // 这里可以根据获取的信息去库中判断是否存在库中 如果不存在执行以下方法
    33.             // 如果该用户不存在数据库中
    34.             // 获取用户信息
    35.             url = ConstantHelper.WX_SCAN_GET_USER_INFO.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
    36.             url = response.encodeURL(url);
    37.             String userResult = HttpClientUtils.get(url, null);
    38.             Map<String, Object> userResultMap = JsonHelper.toMap(userResult);
    39.             // 注册一个用户
    40.             System.out.println("扫码登录返回值******************:" + userResult);
    41.             String headimgurl = (String) userResultMap.get("headimgurl");
    42.             // 处理微信名特殊符号问题 过滤图标
    43.             String nickname = (String) userResultMap.get("nickname");
    44.             // 把用户信息存入session中
    45.         } catch (Exception e) {
    46.             e.printStackTrace();
    47.         }
    48.         // 返回地址
    49.         try {
    50.             String newUrl = request.getParameter("state");
    51.             response.sendRedirect(newUrl);
    52.         } catch (IOException e) {
    53.             // logger.error("url:重定向错误");
    54.         }
    55.     }
    复制代码

    下面附上几个工具类
    1. public class Proxy {
    2.     // const
    3.     public final static int DEFAULT_CONNECT_TIMEOUT = 15000 * 2;
    4.     public final static int DEFAULT_SO_TIMEOUT = 30000 * 2;
    5.     public final static int DEFAULT_BUFFER_SIZE = 256;
    6.     public final static int DEFAULT_MAX_CONNECTIONS = 200 * 2;

    7.     private final static String CS_PREFIX = "charset=";
    8.     private final static int CS_PREFIX_LEN = CS_PREFIX.length();

    9.     // 数据编码格式
    10.     private final String encoding;
    11.     // client
    12.     private final HttpClient client;
    13.     // buffer
    14.     private final int bufferSize;

    15.     public Proxy() {
    16.         this("UTF-8", DEFAULT_CONNECT_TIMEOUT, DEFAULT_SO_TIMEOUT, DEFAULT_BUFFER_SIZE, DEFAULT_MAX_CONNECTIONS);
    17.     }

    18.     public Proxy(final String encoding) {
    19.         this(encoding, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SO_TIMEOUT, DEFAULT_BUFFER_SIZE, DEFAULT_MAX_CONNECTIONS);
    20.     }

    21.     public Proxy(final int bufferSize) {
    22.         this("UTF-8", DEFAULT_CONNECT_TIMEOUT, DEFAULT_SO_TIMEOUT, bufferSize, DEFAULT_MAX_CONNECTIONS);
    23.     }

    24.     public Proxy(final String encoding, final int connectTimeout, final int soTimeout) {
    25.         this(encoding, connectTimeout, soTimeout, DEFAULT_BUFFER_SIZE, DEFAULT_MAX_CONNECTIONS);
    26.     }

    27.     public Proxy(final String encoding, final int connectTimeout, final int soTimeout, final int bufferSize) {
    28.         this(encoding, connectTimeout, soTimeout, bufferSize, DEFAULT_MAX_CONNECTIONS);
    29.     }

    30.     public Proxy(final String encoding, final int connectTimeout, final int soTimeout, final int bufferSize, final int maxConnections) {
    31.         this.encoding = encoding;
    32.         // connect-parameters
    33.         final HttpConnectionManagerParams mp = new HttpConnectionManagerParams();
    34.         mp.setConnectionTimeout(connectTimeout);
    35.         mp.setSoTimeout(soTimeout);
    36.         mp.setStaleCheckingEnabled(true);
    37.         mp.setTcpNoDelay(true);
    38.         mp.setMaxTotalConnections(maxConnections);
    39.         final HttpConnectionManager mgr = new SimpleHttpConnectionManager();
    40.         mgr.setParams(mp);
    41.         // client-init
    42.         this.client = new HttpClient(mgr);
    43.         // client-parameters
    44.         final HttpClientParams cparams = new HttpClientParams();
    45.         // 设置httpClient的连接超时,对连接管理器设置的连接超时是无用的
    46.         cparams.setConnectionManagerTimeout(connectTimeout);
    47.         this.client.setParams(cparams);
    48.         this.bufferSize = bufferSize;
    49.     }

    50.     public HttpClient getClient() {
    51.         return client;
    52.     }

    53.     public String getEncoding() {
    54.         return encoding;
    55.     }

    56.     public String post(final String url, final Map<String, String> headers, final Map<String, String> data, final String encoding) throws HttpException {
    57.         // post方式
    58.         final PostMethod post = new PostMethod(url);
    59.         // headers
    60.         setHeaders(post, headers);
    61.         // content
    62.         if (data != null) {
    63.             Set<Map.Entry<String, String>> postset = data.entrySet();
    64.             final NameValuePair[] params = new NameValuePair[postset.size()];
    65.             int i = 0;
    66.             for (Iterator<Map.Entry<String, String>> it = postset.iterator(); it.hasNext();) {
    67.                 Map.Entry<String, String> p = it.next();
    68.                 params[i++] = new NameValuePair(p.getKey(), p.getValue());
    69.             }
    70.             post.setRequestBody(params);
    71.         }
    72.         try {
    73.             return (execute(post, encoding));
    74.         } finally {
    75.             post.releaseConnection();
    76.         }
    77.     }

    78.     public String post(final String url, final Map<String, String> data, final String encoding) throws HttpException {
    79.         return post(url, null, data, encoding);
    80.     }

    81.     @SuppressWarnings("deprecation")
    82.     public String post(final String url, final Map<String, String> headers, final String data, final String encoding) throws HttpException {
    83.         // post方式
    84.         final PostMethod post = new PostMethod(url);
    85.         // headers
    86.         setHeaders(post, headers);
    87.         // content
    88.         if (data != null) {
    89.             try {
    90.                 final InputStream bin = new ByteArrayInputStream(data.getBytes(this.encoding));
    91.                 post.setRequestBody(bin);
    92.             } catch (final UnsupportedEncodingException e) {
    93.             }
    94.         }
    95.         try {
    96.             return (execute(post, encoding));
    97.         } finally {
    98.             post.releaseConnection();
    99.         }
    100.     }

    101.     public String post(final String url, final String data, final String encoding) throws HttpException {
    102.         // post方式
    103.         return post(url, null, data, encoding);
    104.     }

    105.     public String get(final String url, final Map<String, String> headers) throws HttpException {
    106.         // get方式
    107.         final GetMethod get = new GetMethod(url);
    108.         try {
    109.             // headers
    110.             setHeaders(get, headers);
    111.             return (execute(get, encoding));
    112.         } finally {
    113.             get.releaseConnection();
    114.         }
    115.     }

    116.     private final HttpMethod setHeaders(final HttpMethod method, final Map<String, String> headers) {
    117.         if (headers != null) {
    118.             final Set<Map.Entry<String, String>> headset = headers.entrySet();
    119.             for (Iterator<Map.Entry<String, String>> it = headset.iterator(); it.hasNext();) {
    120.                 Map.Entry<String, String> header = it.next();
    121.                 method.setRequestHeader(header.getKey(), header.getValue());
    122.             }
    123.         }
    124.         return method;
    125.     }

    126.     private String execute(final HttpMethod method, final String encoding) throws HttpException {
    127.         InputStream in = null;
    128.         BufferedReader reader = null;
    129.         try {
    130.             client.executeMethod(method);
    131.             // get-encoding
    132.             String encode = encoding;
    133.             final Header ctypeh = method.getResponseHeader("Content-Type");
    134.             if (ctypeh != null) {
    135.                 final String cv = ctypeh.getValue();
    136.                 final String ctype;
    137.                 if (cv == null) {
    138.                     ctype = null;
    139.                 } else {
    140.                     ctype = cv.toLowerCase(Locale.ENGLISH);
    141.                 }
    142.                 final int i;
    143.                 if (ctype != null && (i = ctype.indexOf(CS_PREFIX)) != -1) {
    144.                     encode = ctype.substring(i + CS_PREFIX_LEN).trim();
    145.                     // test encoding
    146.                     try {
    147.                         "a".getBytes(encode);
    148.                     } catch (UnsupportedEncodingException e) {
    149.                         encode = encoding;
    150.                     }
    151.                     //
    152.                 }
    153.             }
    154.             //
    155.             if (encode == null) {
    156.                 return (method.getResponseBodyAsString());
    157.             }
    158.             in = method.getResponseBodyAsStream();
    159.             reader = new BufferedReader(new InputStreamReader(in, encode), bufferSize);
    160.             final StringBuffer sbuf = new StringBuffer(bufferSize >>> 1);
    161.             for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    162.                 sbuf.append(line).append("\r\n");
    163.             }
    164.             return (sbuf.toString());
    165.         } catch (IOException e) {
    166.             throw new HttpException(e.getMessage());
    167.         } finally {
    168.             if (reader != null) {
    169.                 try {
    170.                     reader.close();
    171.                 } catch (IOException e) {
    172.                 }
    173.             }
    174.             if (in != null) {
    175.                 try {
    176.                     in.close();
    177.                 } catch (IOException e) {
    178.                 }
    179.             }
    180.         }
    181.     }
    182. }
    复制代码
    下面这个工具类是去除微信名中的Emoji表情
    1. public class EmojiFilter {

    2.     /**
    3.      * 检测是否有emoji字符
    4.      * @param source
    5.      * @return 一旦含有就抛出
    6.      */
    7.     public static boolean containsEmoji(String source) {
    8.         if (StringUtils.isBlank(source)) {
    9.             return false;
    10.         }

    11.         int len = source.length();

    12.         for (int i = 0; i < len; i++) {
    13.             char codePoint = source.charAt(i);

    14.             if (isEmojiCharacter(codePoint)) {
    15.                 //do nothing,判断到了这里表明,确认有表情字符
    16.                 return true;
    17.             }
    18.         }

    19.         return false;
    20.     }

    21.     private static boolean isEmojiCharacter(char codePoint) {
    22.         return (codePoint == 0x0) ||
    23.                 (codePoint == 0x9) ||
    24.                 (codePoint == 0xA) ||
    25.                 (codePoint == 0xD) ||
    26.                 ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
    27.                 ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
    28.                 ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    29.     }

    30.     /**
    31.      * 过滤emoji 或者 其他非文字类型的字符
    32.      * @param source
    33.      * @return
    34.      */
    35.     public static String filterEmoji(String source) {

    36.         if (!containsEmoji(source)) {
    37.             return source;//如果不包含,直接返回
    38.         }
    39.         //到这里铁定包含
    40.         StringBuilder buf = null;

    41.         int len = source.length();

    42.         for (int i = 0; i < len; i++) {
    43.             char codePoint = source.charAt(i);

    44.             if (isEmojiCharacter(codePoint)) {
    45.                 if (buf == null) {
    46.                     buf = new StringBuilder(source.length());
    47.                 }

    48.                 buf.append(codePoint);
    49.             } else {
    50.             }
    51.         }

    52.         if (buf == null) {
    53.             return source;//如果没有找到 emoji表情,则返回源字符串
    54.         } else {
    55.             if (buf.length() == len) {//这里的意义在于尽可能少的toString,因为会重新生成字符串
    56.                 buf = null;
    57.                 return source;
    58.             } else {
    59.                 return buf.toString();
    60.             }
    61.         }

    62.     }
    63. }
    复制代码


    如果您有业务需求,可以和我联系:http://wpa.qq.com/msgrd?V=3&amp; ... yes&amp;from=discuz
    回复

    使用道具 举报

    快速回复: 支持 高兴 激动 给力 加油 苦寻 生气 回帖 路过 感恩
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    首页|Archiver|手机版|小黑屋|密通学院:专业网络营销服务商

    GMT+8, 2024-5-8 22:23 , Processed in 0.107422 second(s), 27 queries QQ

    Powered by XMT Inc. © 2015-2025 ArrayV1.0 豫ICP备17022382号

    系统运营:密城通 豫公网安备 41018302000212 号

    快速回复 返回顶部 返回列表