SpringBoot 獲取微信小程序openid


最近做一個項目用到小程序,為了簡化用戶啊登錄,通過獲取小程序用戶的openid來唯一標示用戶。

1、官方教程

2、具體步驟

3、具體實現

4、可能出現的錯誤

5、代碼下載

 

1、官方教程

先來看看官方怎么說的:官方鏈接

官方的意思是用戶打開小程序會產生一個臨時的code(code有實效性),通過這個code加上一些參數作 可以獲取openID和sessionKey。

 

 

 

 

具體需要什么參數呢?官方介紹

 

 

2,具體步驟

A,拿到appid和appsecret

B,通過小程序wx.login({...}); 函數獲取code

C,把code、appid、secret、type作為參數 發送給服務器換取 openID

 

3,具體實現

由於code是用戶登錄是產生的,grat_type是默認的,所以只要再拿到appIDappSecret

小程序的 appId 和小程序的 appSecret獲取方法:

A:登錄微信公眾平台 https://mp.weixin.qq.com

B:找到開發

 

 

小程序客戶端獲取code

在小程序app.js 中加入 下面的代碼:當編譯工程時會自動發送請求並且把code發送給服務器。

// 登錄
    wx.login({
      success: res => {
        // 發送 res.code 到后台換取 openId, sessionKey, unionId
        if (res.code) {
          wx.request({
            url: 'http://localhost:8080/cis',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
              console.log("openid:" + res.data.openid);
              if (res.data.openid != "" || res.data.openid != null) {
                // 登錄成功
                wx.setStorageSync("openid", res.data.openid);//將用戶id保存到緩存中
                wx.setStorageSync("session_key", res.data.session_key);//將session_key保存到緩存中
              } else {
                // 登錄失敗
                // TODO 跳轉到錯誤頁面,要求用戶重試


                return false;
              }
            }
          })
        } else {
          console.log('獲取用戶登錄態失敗!' + res.errMsg)
        }
      }
    })
  

 

服務端用idea建立springboot工程 導入web依賴

A:

 

 

B:

 

 

C:

 

 

D:

在pom.xml中引入依賴:

     <!--Http Requset封裝-->
        <!--http requset-->
        <dependency>
            <groupId>com.github.kevinsawicki</groupId>
            <artifactId>http-request</artifactId>
            <version>6.0</version>
        </dependency>

        <!--json 解析-->
        <!--https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>

E:

建立controller包和server包,在server包下創建impl包:

 

 WeChatController類用來處理請求,接收參數(code),代碼如下:

import com.cnetopro.httpdemo.service.WeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WeChatController {
    @Autowired
    WeChatService wc;

    @RequestMapping("/cis")
    public void getcode(@RequestParam(value = "code")String  code){
        System.out.println(code);

       wc.codetoopenid(code);

    }
}

WeChatService接口用來 發送get請求獲取openID和sessionkey,代碼如下

import org.springframework.stereotype.Service;


public interface WeChatService {
    public String codetoopenid(String code);
}

WeChartServiceimpl類用來實現WeChartService里面的方法,代碼如下

注意把xxxx...替換成自己的 appid

把eeeeee...替換成自己的secret

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cnetopro.httpdemo.service.WeChatService;
import com.github.kevinsawicki.http.HttpRequest;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceimpl implements WeChatService {

    @Override
    public String codetoopenid(String code) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("appid", "xxxxxxxxxxxxxxxxx");
        data.put("secret", "eeeeeeeeeeeeeeeeeeeeeeeeee");
        data.put("js_code", code);
        data.put("grant_type", "authorization_code");


        String response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
        System.out.println("Response was: " + response);
        JSONObject obj= JSON.parseObject(response);//將json字符串轉換為json對
        System.out.println(obj);



        return null;
    }
}

 

運行結果:

成功獲取openID和sessionkey

 

 

 

WeChatServiceimpl代碼說明:

用這個jar包來封裝https請求

  <!--http requset-->
        <dependency>
            <groupId>com.github.kevinsawicki</groupId>
            <artifactId>http-request</artifactId>
            <version>6.0</version>
        </dependency>

用這個jar包來處理接收的數據

 

       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>

 

 

4、可能出現的錯誤說明

1.小程序

 錯誤:http://localhost:8080 不在以下 request 合法域名列表中,請參考文檔

解決辦法:點擊小程序開發工具右上角詳情>本地設置>不校驗合法域名

 

2.idea開發工具控制台報錯

(這個錯誤困擾了3個小時)

 {"errcode":40013,"errmsg":"invalid appid, hints: [ req_id: dHMAcEyFe-9lrrvA ]"}

錯誤原因1: appId填錯了

錯誤原因2:secret填錯了

錯誤原因3(非常重要):微信開發着工具創建小程序時的appId與 服務器端代碼的appId不一致,(因為有時喜歡用接口測試號appid)

 

5、代碼下載

github:下載地址

gitee:下載地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM