【微信開發】免費域名—網頁授權獲取用戶openid

在這裏插入圖片描述

最近在接觸微信支付開發,要進行微信支付就需要用戶的唯一標識——openid,因爲第一次接觸踩了很多坑,於是就把他記錄下來,也便於以後查閱,也方便有需要的人進行參考

本文中的所使用的源碼都會在給出地址。可放心瀏覽

一、openid?

openid是微信用戶在公衆號appid下的唯一用戶標識(appid不同,則獲取到的openid就不同),
可用於永久標記一個用戶,同時也是微信JSAPI支付的必傳參數。

二、準備工具

工欲善其事必先利其器,不管做什麼我們先要把準備工作做好,比如寫代碼的時候,可以先把具體的思路寫在代碼塊裏面,第一步做什麼第二步做什麼,咳咳,說的有點遠了,迴歸正題,在微信開發中最重要的一個就是 官方文檔 ,所以一定要仔細閱讀文檔,下面就是我們需要微信開發中需要的工具:

1、公網域名NATApp
2、官方文檔網頁授權獲取用戶openid接口文檔
3、測試賬號測試號

2.1、免費公網域名

1、首先我們登錄到NATApp官網中,進行註冊登錄,登錄後,進入以下頁面,點擊 購買隧道 > 免費隧道

在這裏插入圖片描述
2、購買免費隧道
我們需要設置就是一個本地端口,也就是你可以 提供服務的端口(tomcat端口),點擊免費購買
在這裏插入圖片描述
3、點擊 我的隧道 ,查看剛纔創建的隧道,這裏要留意 authtoken 我們下面會使用到
在這裏插入圖片描述
4、點擊列表中 配置,修改配置,除了本地地址和端口,其他的默認即可
本地地址:127.0.0.1 即可
端口:tomcat端口,博主的是 8080

在這裏插入圖片描述

5、點擊客戶端下載,這裏以 win64 爲例
在這裏插入圖片描述
在這裏插入圖片描述
6、將安裝包解壓,會看到一個natapp.exe的文件,雙擊運行
在這裏插入圖片描述
7、下面的提示錯誤,可以忽略,不會影響我們正常使用
在這裏插入圖片描述
8、輸入命令 natapp -authtoken 4526sdfe44,注意 4526sdfe44 是你自己的 authtoken,在 我的隧道 列表中可以看到 authtoken,上文 第3點 中有說到
注意:不要 點擊複製 按鈕,沒有效果
在這裏插入圖片描述
9、下面就是我們成功創建 隧道和本地的鏈接了

http://kxfmfu.natappfree.cc -> 127.0.0.1:8080

#就是我們需要使用的域名
http://kxfmfu.natappfree.cc 
#本地IP和端口
127.0.0.1:8080

免費隧道域名是系統隨機分配,可以的話,花9塊錢買一個固定的隧道也是可以的,有效期是一個月
在這裏插入圖片描述
Ctrl+C #退出系統

10、測試,通過域名訪問
新建一個項目,在瀏覽器能訪問就行,這裏就不做詳細介紹了

測試代碼:

/**
 * @program: weixin_demo
 * @ClassName WeiXinController
 * @description:
 * @author: lyy
 * @create: 2019-11-12 10:16
 * @Version 1.0
 **/
@RestController
@RequestMapping("weixin")
@Slf4j
public class WeiXinController {
    @GetMapping("test")
    public String auth(){
        log.info("test進來了。。。");
        return "test測試";
    }
}

訪問成功:
在這裏插入圖片描述

2.2、授權獲取用戶openid接口文檔

網頁授權獲取用戶openid接口文檔
在這裏插入圖片描述

2.3、測試賬號:

點擊:測試號

1、設置域名回調

開發者需要先到公衆平臺官網中的“開發 - 接口權限 - 網頁服務 - 網頁帳號 - 網頁授權獲取用戶基本信息”的
配置選項中,修改授權回調域名。請注意,這裏填寫的是域名(是一個字符串),而不是URL,因此請勿
加 http:// 等協議頭;

也就是說在微信公衆號請求用戶網頁授權之前,也就是微信開發之前,填入我們所要開發的域名,這裏我們使用的是測試環境,所以需要在測試賬號管理頁面 網頁帳號 > 網頁授權獲取用戶基本信息 填入我們自己的域名,這裏要注意填入域名的規則,這裏填寫的是域名(是一個字符串),而不是URL,因此請勿加 http:// 等協議頭
在這裏插入圖片描述
在這裏插入圖片描述
2、設置成功後,我們就可以看到我們設置的,JS接口安全域名,如果需要修改點擊 JS接口安全域名 修改 中的 修改

要登錄測試號後,我們纔可以進行測試
在這裏插入圖片描述

3、測試號設置完成,接口配置信息不需要進行配置
在這裏插入圖片描述

三、微信開發

第一步:用戶同意授權,獲取code

在確保微信公衆賬號擁有授權作用域(scope參數)的權限的前提下(服務號獲得高級接口後,默認擁有scope參數中的snsapi_base和snsapi_userinfo),引導關注者打開如下頁面:

# 若提示“該鏈接無法訪問”,請檢查參數是否填寫錯誤,是否擁有scope參數對應的授權作用域權限。
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 

參數說明:
在這裏插入圖片描述
將我們剛纔在測試號中填寫的信息放入對應的參數中:
appID :在我們測試號信息中有
redirect_uri:鏈接地址,是我們在代碼中編寫的地址,文檔上說:請使用 urlEncode 對鏈接進行處理,其實做不做 urlEncode 都可以訪問
scope:這裏有 snsapi_basesnsapi_userinfo兩種,因爲我們需要拿到用戶的信息(openid)所以使用 snsapi_userinfo

  • snsapi_base (不彈出授權頁面,直接跳轉,只能獲取用戶openid)
  • snsapi_userinfo (彈出授權頁面,可通過openid拿到暱稱、性別、所在地

獲取code:

1、代碼:

/**
 * @program: weixin_demo
 * @ClassName WeiXinController
 * @description:
 * @author: lyy
 * @create: 2019-11-12 10:16
 * @Version 1.0
 **/
@RestController
@RequestMapping("weixin")
public class WeiXinController {


    @GetMapping("test")
    public String auth(@RequestParam("code") String code){
        System.out.println(code);
        return code;
    }
}

2、編輯連接:

可以直接在文件助手中打開:
我的連接:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的AppID&redirect_uri=http://域名/weixin/test&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
在這裏插入圖片描述
成功返回code:
在這裏插入圖片描述

第二步:正式開發,獲取用戶openid

當我們把第一步成功之後,下面的步驟就非常簡單了,只需要按照微信文檔的說明一步步往下走就可以了,你以爲這麼簡答嗎?其實是的,但是我們在這裏要介紹一個第三方的SDK包——WxJava ,用來幫助我們更好更快的使用微信開發,感興趣的可以瞭解下

WxJavahttps://github.com/Wechat-Group/WxJava
在這裏插入圖片描述
目錄結構:
在這裏插入圖片描述

2.1 導入jar包:
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-mp</artifactId>
    <version>3.5.0</version>
</dependency>
2.2 源碼:

WeChatController

package com.weixin.controller;

import com.weixin.config.WeixinUrlConfig;
import com.weixin.enums.ResultEnum;
import com.weixin.exception.WeixinException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 * @program: sell
 * @ClassName WeChatController
 * @description:
 * @author: lyy
 * @create: 2019-11-12 21:37
 * @Version 1.0
 **/
@Controller
@RequestMapping("wechat")
@Slf4j
public class WeChatController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WeixinUrlConfig weixinUrlConfig;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){

        //1. 配置
        //2. 調用方法
        String url = weixinUrlConfig.getWechatMpAuthorize()+"/wechat/userInfo";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("【微信網頁授權獲取code,result={}】",redirectUrl);

        return "redirect:"+redirectUrl;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl) {
        log.info("進入userInfo信息表裏面");

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信網頁授權】{}", e);
            throw new WeixinException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();

        return "redirect:" + returnUrl + "?openid=" + openId;
    }


}

WeixinUrlConfig

package com.weixin.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @program: sell
 * @ClassName ProjectUrlConfig
 * @description:
 * @author: lyy
 * @create: 2019-11-12 21:41
 * @Version 1.0
 **/
@Data
@Component
@ConfigurationProperties(prefix = "projecturl")
public class WeixinUrlConfig {

    /**
     * 微信公衆平臺授權url
     */
    public String wechatMpAuthorize;


}

WechatMpConfig

package com.weixin.config;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @program: sell
 * @ClassName ProjectUrlConfig
 * @description:
 * @author: lyy
 * @create: 2019-11-12 21:41
 * @Version 1.0
 **/
@Component
public class WechatMpConfig {

    @Autowired
    private WechatAccountConfig accountConfig;

    @Bean
    public WxMpService wxMpService(){
        System.out.println("wxMpService");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
        return wxMpService;
    }

    @Bean
    public WxMpConfigStorage wxMpConfigStorage(){
        System.out.println("wxMpConfigStorage(),{}"+accountConfig.getMpAppId());
        WxMpDefaultConfigImpl wxMpConfigStorage = new WxMpDefaultConfigImpl();
        wxMpConfigStorage.setAppId(accountConfig.getMpAppId());
        wxMpConfigStorage.setSecret(accountConfig.getMpAppSecret());
        return wxMpConfigStorage;
    }

}

配置文件:application.yml
注意:這裏的配置文件需要填你自己的信息

wechat:
  mpAppId: wxbd885se5e5se53
  mpAppSecret: 3a6bsdf85sdf5wesd5fwesd5fwesdfde

projecturl:
  wechatMpAuthorize: http://xxyyg.n52y00.top

第三步:測試,拿到openId

輸入鏈接:
http://域名/wechat/authorize?returnUrl=https://www.baidu.com/
在這裏插入圖片描述
打開我們填寫的網站:www.baidu.com,點擊複製鏈接地址,我們就可以看到我們帶過來的 openId

https://www.baidu.com/?openid=oMU7C1246578976kCEsrAcE
在這裏插入圖片描述

三、總結

總體看來還是很簡單,但是還是需要注意一些細節,不然就很容易卡在那裏,一定要對照着官方文檔進行開發,仔細閱讀,好了,今天就到這裏,有問題或者不懂的小夥伴留言或者私信我,小農看到後會第一時間回覆大家,謝謝。

雙手奉上源碼地址:https://github.com/839022478/weixin/

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