小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

springboot 微信小程序用codeid換取openid

 印度阿三17 2019-06-30

1.首先我們需要去微信公眾平臺
https://mp.weixin.qq.com/
準備的是AppID(小程序ID)和AppSecret(小程序密鑰)
在這里插入圖片描述
2.準備好后開始寫代碼
3.controller

@RestController
public class GetOpenIdController {
    /**
     * 功能描述:
     * 微信小程序用codeid換取openid
     * @param codeId
     * @return
     */
    @GetMapping("/onLogin")
    private HttpResponseEntity onLogin(String codeId){
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String openid = RedisUtils.getOpenId(codeId);
            System.err.println(openid);
            httpResponseEntity.setCode(Constans.SUCCESS_CODE);
            httpResponseEntity.setMessage(Constans.RESULT_SUCCESS);
            httpResponseEntity.setData(openid);
        }catch (Exception e){
            e.printStackTrace();
            httpResponseEntity.setMessage(Constans.RESULT_EXIST);
            httpResponseEntity.setCode(Constans.ADD_EXIST_CODE);
        }
        return httpResponseEntity;
    }
}

4.RedisUtils

/**
     * 獲取小程序codeid換取openid
     * @param codeId
     * @return
     */
    public static String getOpenId(String codeId) {
        String url = CODE_URL   APP_ID   "&secret="   SECRET   "&js_code="   codeId   "&grant_type=authorization_code";
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();

            // 設置通用的請求屬性 設置請求格式
            //設置返回類型
            conn.setRequestProperty("contentType", "text/plain");
            //設置請求類型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //設置超時時間
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // flush輸出流的緩沖
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應    設置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
            return jsonObject.get("openid").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
/**
     *  根據(jù)code換取openId
     *  本接口應在后端服務器調(diào)用
     */
    private final static String CODE_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=";

    private final static String APP_ID = "AppID(小程序ID)";

    private final static String SECRET = "AppSecret(小程序密鑰)";

CODE_URL為請求地址
這樣后臺就完成了(封裝的返回結果集這里就不展示了)

微信小程序端:

新建一個小程序
修改app.js就好

//app.js
App({
  onLaunch: function () {
    var that = this;
    // 展示本地存儲能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登錄
    wx.login({
      success: function(res) {
        // 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
      if(res.code){
        wx.request({
          url: 'http://localhost:8080/onLogin',
          data:{
            codeId:res.code
          },
          success: res => {
            console.log(res);
            res.data.openid = res.data.data;
            that.globalData.openid = res.data.openid;
            console.log(that.globalData.openid);
          }
        })
      }else{
        console.log("獲取用戶登錄失敗!"   res.errMsg)
      }
    }
  })
    // 獲取用戶信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已經(jīng)授權,可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會彈框
          wx.getUserInfo({
            success: res => {
              // 可以將 res 發(fā)送給后臺解碼出 unionId
              this.globalData.userInfo = res.userInfo
              console.log(res);
              // 由于 getUserInfo 是網(wǎng)絡請求,可能會在 Page.onLoad 之后才返回
              // 所以此處加入 callback 以防止這種情況
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    openid:null
  }
})

這樣就基本完成了
我們來運行下看看效果:
在這里插入圖片描述
在這里插入圖片描述

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多