慕課網_《微信受權登陸》學習總結

時間:2017年08月12日星期六
說明:本文部份內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...java

第一章:課程介紹

1-1 課程介紹

課程內容mysql

課程介紹
登陸方式介紹
基於微信公衆號受權登陸
微信開放平臺介紹
基於微信開放平臺實現受權登陸
微信公衆號與微信開放平臺關聯整合

第二章:登陸方式介紹

2-1 登陸方式介紹

微信登陸介紹git

微信開放平臺
微信公衆號(微信公衆平臺)

手機受權登陸頁github

clipboard.png

實現方式web

沒有本身的帳號體系,直接拉取微信用戶信息來進行網站登陸。
有本身的帳號體系,受權成功後須要綁定本身的帳號。

第三章:基於公衆號的登陸

3-1 公衆號受權登陸

接口文檔spring

路徑:微信網頁開發》微信網頁受權
地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

建立名爲wxdevauth的maven項目,POM文件以下sql

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myimooc</groupId>
    <artifactId>wxdevauth</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>wxdevauth</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.36</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        
        <dependency>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
            </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

完成後的項目結構以下apache

clipboard.png

說明:因爲條件限制,此項目代碼均沒有進行測試,這裏只是顯示大概開發過程。json

代碼演示:api

1.編寫User類

package com.myimooc.wxdevauth.wxauth.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * 自有用戶帳號體系
 * @author ZhangCheng on 2017-08-12
 *
 */
@Entity
public class User {
    
    @Id
    @GeneratedValue
    private Long id;
    private String account;
    private String password;
    private String nickname;
    private String openid;
    private String unionid;
    
    @Override
    public String toString() {
        return "User [id=" + id + ", account=" + account + ", password=" + password + ", nickname=" + nickname
                + ", openid=" + openid + "]";
    }
    
    public String getUnionid() {
        return unionid;
    }

    public void setUnionid(String unionid) {
        this.unionid = unionid;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getAccount() {
        return account;
    }
    public void setAccount(String account) {
        this.account = account;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public String getOpenid() {
        return openid;
    }
    public void setOpenid(String openid) {
        this.openid = openid;
    }
    
    
    
}

2.編寫UserRepository類

package com.myimooc.wxdevauth.wxauth.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.myimooc.wxdevauth.wxauth.domain.User;

/**
 * 用戶相關資源類
 * @author ZhangCheng on 2017-08-12
 *
 */
public interface UserRepository extends JpaRepository<User, Long> {
    
    User findByunionid(String unionid);
    
}

3.編寫AuthUtils類

package com.myimooc.wxdevauth.wxauth.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 使用Http進行認證請求
 * @author ZhangCheng on 2017-08-12
 *
 */
public class AuthUtils {
    
    public static final String APPID="dsadqawer2124a5wdqw1";
    public static final String APPSECRET = "dsadaq875w5edqwd58qwdqwbgthr4t5qa";
    private static final String CHARSET_FORMAT = "UTF-8";
    
    /**
     * 發起GET請求,並將響應數據封裝爲JSON
     */
    public static JSONObject doGetJson(String url) throws Exception{
        JSONObject jsonObject = null;
        HttpClientBuilder  builder = HttpClientBuilder.create();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = builder.build().execute(httpGet);
        HttpEntity entity = response.getEntity();
        if(null != entity){
            String result = EntityUtils.toString(entity,CHARSET_FORMAT);
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }
    
}

4.編寫LoginRest類

package com.myimooc.wxdevauth.wxauth.rest;

import java.net.URLEncoder;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.myimooc.wxdevauth.wxauth.domain.User;
import com.myimooc.wxdevauth.wxauth.repository.UserRepository;
import com.myimooc.wxdevauth.wxauth.util.AuthUtils;

/**
 * 登陸認證REST
 * @author ZhangCheng on 2017-08-12
 *
 */
@Controller
public class LoginRest {
    
    @Autowired
    private UserRepository userRepository;
    
    @RequestMapping(value={"/","","/index"})
    public ModelAndView index(){
        return new ModelAndView("index");
    }
    
    /**
     * 第一步:用戶贊成受權,獲取code
     * 入口地址
     */
    @RequestMapping("wxlogin")
    public Object doLogin(HttpServletRequest req){
        // 用戶受權後微信回調地址
        String backUrl = "/callback";
        @SuppressWarnings("deprecation")
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtils.APPID
                + "&redirect_uri="+URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_userinfo "
                + "&state=STATE#wechat_redirect";
        
        return "redirect:"+url;
    }
    
    /**
     * 第二步:經過code換取網頁受權access_token
     * 回調地址-獲得code,從而去得到access_token 和 openid
     */
    @RequestMapping("/callback")
    public ModelAndView doCallBack(HttpServletRequest req)throws Exception{
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtils.APPID
                + "&secret="+AuthUtils.APPSECRET
                + "&code="+code
                + "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtils.doGetJson(url);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        // 第三步:刷新access_token(若是須要)
        // 此處省略
        
        // 第四步:拉取用戶信息(需scope爲 snsapi_userinfo)
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
                + "&openid="+openid
                + "&lang=zh_CN";
        JSONObject userInfo = AuthUtils.doGetJson(infoUrl);
        System.out.println("用戶信息:"+userInfo);
        ModelAndView mv = new ModelAndView("success");
        mv.addObject("info",userInfo);
        String unionid = userInfo.getString("unionid");
        
        // 1.使用微信用戶信息直接登陸,無須註冊和綁定,直接跳轉到登陸成功界面
        //ModelAndView mv = new ModelAndView("success");
        //mv.addObject("info",userInfo);
        //return mv;
        
        // 2.將微信與當前系統的帳號進行綁定,綁定後跳轉到登陸成功界面
        User user = userRepository.findByunionid(unionid);
        if(null != user && (!Objects.equals("", user.getNickname()))){
            // 已綁定,直接跳轉綁定成功的頁面
            mv.setViewName("bindsuccess");
            mv.addObject("nickname", user.getNickname());
            return mv;
        }else{
            // 未綁定,跳轉到本身系統的登陸頁面
            mv.setViewName("login");
            mv.addObject("unionid", unionid);
            return mv;
        }
    }
    
    /**
     * 登陸並綁定微信帳號
     */
    @PostMapping("/bindwx")
    public Object bindwx(User user){
        userRepository.save(user);
        return "帳號綁定成功";
    }
}

第四章:微信開放平臺介紹

4-1 微信開放平臺介紹

微信開放平臺

地址:https://open.weixin.qq.com/

註冊並登陸成功後,需進行開發者認證

clipboard.png

第五章:基於開放平臺登陸

5-1 開放平臺受權登陸

接口文檔

路徑:網站應用》網站應用微信登陸開發指南
地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN

開發方式與使用微信公衆號登陸的方式相似,僅僅多是調用的微信接口地址不一樣而已,就不提供代碼演示了,源碼請到個人github地址查看。

第六章:公衆號與開發平臺關聯

6-1 公衆號與開放平臺關聯

情景說明:

當使用pc端進行微信受權登陸時,獲得的openid和公衆號受權登陸時獲得的openid不同。

爲何不同

當咱們在微信公衆號裏面綁定了而且受權了應用A的時候,會產生一個openid。而在開放平臺受權應用A的時候,又會參數另一個openid。它們兩個是徹底獨立的,即微信公衆號與開放平臺之間是相互獨立的,它們之間並無關聯關係。

在開放平臺裏面綁定公衆帳號

clipboard.png

開放平臺與公衆帳號之間的關係是如何體現的

使用UnionID機制

什麼是UnionID機制

好比像萬達集團,萬達影業與萬達百貨但願作到會員卡通用。
微信在這裏作了一個打通機制,對於同一個企業,在用戶屬性裏面加了一個企業屬性(UnionID),
方便同一個企業在不一樣的產品中識別到同一個用戶。

如何識別是同一個企業

只要綁定在同一個開放平臺下全部移動應用、網站應用、微信公衆號都具有同一個UnionID

即在綁定微信帳號時,再也不使用openid字段進行綁定,使用unionid字段進行綁定便可。

相關文章
相關標籤/搜索