手把手教你學習基於oauth2.0協議——微信公衆平臺微信網頁授權登錄

1.登錄微信公衆平臺

在對接微信授權時可以使用測試賬號進行操作,當然你也可以使用進行企業認證的公衆號進行對接,此次對接使用測試賬號

微信沙箱賬號鏈接,點擊該鏈接使掃碼登錄測試公衆平臺,登錄後如下:

2.在測試平臺下方,使用開發者的微信關注該測試平臺

3.點擊修改,添加授權回調頁面域名,如下:

這裏的域名地址可以使用外網映射工具進行映射,可以參考natapp的安裝配置教程

4.編碼

4.1.添加依賴到pom.xml中

   <!-- SpringBoot 對lombok 支持 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- SpringBoot web 核心組件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

.4.2.修改application.yml配置文件

#該APPID,secret爲測試公衆平臺的數據
appid: wx6c470ce4236b64fa
secret: 1a82d6d1cefa6ae818c9753c9200d2e5
#使用外網映射工具映射回調地址
redirectUri: http://xi4jsd.natappfree.cc/callback
### 生成微信授權
authorizedUrl: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
###獲取code後,請求以下鏈接獲取access_token
access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
###拉取用戶信息(需scope爲 snsapi_userinfo)
userinfo: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

4.3.創建一個微信的工具類,方便調用


@Component
public class WeiXinUtils {
    @Value("${appid}")
    private String appId;
    @Value("${secret}")
    private String secret;
    @Value("${redirecturi}")
    private String redirectUri;
    @Value("${authorizedUrl}")
    private String authorizedUrl;
    @Value("${access_token}")
    private String accessToken;
    @Value("${userinfo}")
    private String userinfo;

    /**
     * @Description: 微信授權地址
     */
    public String getAuthorizedUrl() {
        return authorizedUrl.replace("APPID", appId).replace("REDIRECT_URI", URLEncoder.encode(redirectUri));
    }

    /**
     * @Description: 獲取微信AccessToken
     */
    public String getAccessTokenUrl(String code) {
        return accessToken.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
    }

    /**
     * @Description: 獲取微信用戶信息
     */
    public String getUserInfo(String accessToken, String openId) {
        return userinfo.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
    }

}

4.4.創建一個授權的控制器,此處沒有寫在業務層,可以自己寫在業務層

@Slf4j
@Controller
public class AuthController {

    @Autowired
    private WeiXinUtils weiXinUtils;
    private String errorPage = "errorPage";
    private static RequestConfig requestConfig = null;

    /**
     * @Description: 獲取授權鏈接,重定向到微信開發平臺
     */
    @GetMapping("/authorizedUrl")
    public String authUrl() {
        String authorizedUrl = weiXinUtils.getAuthorizedUrl();
        return "redirect:" + authorizedUrl;
    }

    @RequestMapping("/callback")
    @ResponseBody
    public String callback(String code) {
        if (StringUtils.isEmpty(code)){
            return errorPage;
        }
        // 1.使用Code 獲取 access_token
        String accessTokenUrl = weiXinUtils.getAccessTokenUrl(code);
        //2.使用HTTPclient技術調用 accessTokenUrl 接口地址
        JSONObject resultAccessToken = httpGet(accessTokenUrl);
        //3.判斷返回的json是否正確,當含有errorcode時,則爲報錯信息
        boolean errcodeKey = resultAccessToken.containsKey("errcode");
        if (errcodeKey) {
            return errorPage;
        }
        // 4.使用access_token獲取用戶信息
        String accessToken = resultAccessToken.getString("access_token");
        if (StringUtils.isEmpty(accessToken)){
            return errorPage;
        }
        //5.獲取openid
        String openid = resultAccessToken.getString("openid");
        if (StringUtils.isEmpty(openid)){
            return errorPage;
        }
        // 6.獲取用戶信息(需scope爲 snsapi_userinfo)
        String userInfoUrl = weiXinUtils.getUserInfo(accessToken, openid);
        JSONObject userInfoResult = httpGet(userInfoUrl);
        log.info("userInfoResult:" + userInfoResult);
        return userInfoResult.toJSONString();
    }

    /**
     * 發送get請求
     * @param url  請求路徑
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get請求返回結果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 發送get請求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 請求發送成功,並得到響應
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 讀取服務器返回過來的json字符串數據
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串轉換成json對象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                log.error("get請求提交失敗:" + url);
            }
        } catch (IOException e) {
            log.error("get請求提交失敗:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

}

5.啓動服務進行測試

測試使用微信web開發者工具 下載地址,安裝該工具後使用關注過測試公衆平的的微信用戶進行登錄測試

5.1.輸入獲取授權鏈接的接口地址

http://127.0.0.1:8080/authorizedUrl

5.2.同意授權,進行異步回調

 

5.3.返回授權用戶的用戶數據

5.4.好了 你可以使用用戶收據了

碼雲地址:https://gitee.com/gts_leo/weixin_oauth2.0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章