免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
springboot 微信小程序用codeid換取openid

1.首先我們需要去微信公眾平臺
https://mp.weixin.qq.com/
準備的是AppID(小程序ID)和AppSecret(小程序密鑰)


2.準備好后開始寫代碼
3.controller

@RestControllerpublic 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     *  本接口應在后端服務器調用     */    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.jsApp({  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']) {          // 已經授權,可以直接調用 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  }})

這樣就基本完成了
我們來運行下看看效果:


本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
微信小程序支付簡單小結與梳理
JAVA版微信支付V3-完全版
Flask 微信卡券小項目:從開發(fā)到上線
微信小程序接入微信支付,只需3步
實戰(zhàn) | 打造一個雙端自動發(fā)布的博客體系(下)
SpringCloud 微信小程序登錄 方案一【SpringCloud系列13】
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服