国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

微信小程序——獲取用戶手機(jī)號(hào)(Java后臺(tái))

這篇具有很好參考價(jià)值的文章主要介紹了微信小程序——獲取用戶手機(jī)號(hào)(Java后臺(tái))。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

最后有完整代碼
1、獲取code

onShow: function() {
   var that = this;
         //獲取用戶的本地緩存數(shù)據(jù),userinfo信息是在用戶授權(quán)登錄時(shí)保存的
         var n = wx.getStorageSync("userinfo");
         //當(dāng)本地緩存的用戶名稱不為""或者null時(shí),設(shè)置userinfo信息
         if(n.nickName != '' && n.nickName != null){
             this.setData({
                 userinfo: n,
                 hasUserInfo:true,
                 canIUseGetUserProfile:true
             })
             // 通過wx.login獲取登錄憑證(code),然后通過code去獲取我們用戶的openid
             wx.login({
               success:(res)=>{
                   console.log(res);
                   that.getOpenId();
               },
             })
         }
 },

2、利用code獲取sessionkey
小程序端:

getOpenId(){
   var that=this
  wx.login({
    success (res) {
      if (res.code) {
        //發(fā)起網(wǎng)絡(luò)請(qǐng)求
        wx.request({
          url: '自己的Control路徑',
          data: {
            code: res.code
          },
          method: 'get',
          header: {
            'content-type': 'application/json' //默認(rèn)值
          },
          success: function(res) { //res就是接收后臺(tái)返回的數(shù)據(jù)
            console.log(res.data);
            that.setData({
              sessionkey:res.data
            })
          },
        })
      } else {
        console.log('登錄失敗!' + res.errMsg)
      }
    }
  })
 },
  

Java后臺(tái):

 @RequestMapping("名稱")                             //獲取sessionid
    @ResponseBody
    public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String appId="自己的appid";
        String secret="小程序密鑰";
        String code=request.getParameter("code");
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //這三個(gè)參數(shù)就是之后要填上自己的值。
        //替換appid,appsecret,和code
        String requestUrl = url;
        //調(diào)用get方法發(fā)起get請(qǐng)求,并把返回值賦值給returnvalue
        String  returnvalue=GET(requestUrl);
        System.out.println(requestUrl);//打印發(fā)起請(qǐng)求的url
        System.out.println(returnvalue);//打印調(diào)用GET方法返回值
        //定義一個(gè)json對(duì)象。
        JSONObject convertvalue=new JSONObject();

        //將得到的字符串轉(zhuǎn)換為json
        convertvalue=(JSONObject) JSON.parse(returnvalue);


        System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
        System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
        //把openid和sessionkey分別賦值給openid和sessionkey
        String openid=(String) convertvalue.get("openid");
        String sessionkey=(String) convertvalue.get("session_key");//定義兩個(gè)變量存儲(chǔ)得到的openid和session_key.
        Gson gson=new Gson();
        String json = gson.toJson(sessionkey);
        Writer out = response.getWriter();
        out.write(String.valueOf(json));
        out.flush();
    }
    //發(fā)起get請(qǐng)求的方法。
    public static String GET(String url) {
        System.out.println("start");//打印發(fā)起請(qǐng)求的url
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // 異常記錄
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 異常記錄
            }
        }
        return result;
    }

獲取小程序密鑰:微信公眾平臺(tái)->開發(fā)管理->開發(fā)設(shè)置
3、獲取iv和encryptedData并解密獲取手機(jī)號(hào)

getPhoneNumber(e) { 
   var that=this;
   console.log("手機(jī)號(hào):") 
   wx.request({
    url: '自己的Control路徑',
    data: {
      sessionkey: that.data.sessionkey,
      iv:e.detail.iv,
      encryptedData:e.detail.encryptedData
    },
    method: 'get',
    header: {
      'content-type': 'application/json' //默認(rèn)值
    },
    success: function(res) { //res就是接收后臺(tái)返回的數(shù)據(jù)
      console.log(res.data);
    },
  })
 } 

java后臺(tái):

@RequestMapping("decryptS5")                      //解密獲取手機(jī)號(hào)
    @ResponseBody
    public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sSrc=request.getParameter("encryptedData");
        String encodingFormat="utf-8";
        String sKey=request.getParameter("sessionkey");
        String ivParameter=request.getParameter("iv");
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            System.out.println(new String(original, encodingFormat));
            return new String(original, encodingFormat);
        } catch (Exception ex) {
            return null;
        }
    }

如果報(bào)錯(cuò)40029則可能是appid不對(duì)
4、完整代碼
wxml:

<!--index.wxml-->
<view class="banner">
    <view class="topContainer">
        <view catchtap="showBcgImgArea">
            <image class="userinfo-avatar" mode="aspectFill" src="{{userinfo.avatarUrl}}"></image>
        </view>
        <view>
            <text class="userinfo-nickname">{{userinfo.nickName}}</text>
        </view>
    </view>
    <button wx:if="{{!hasUserInfo && canIUseGetUserProfile}}" open-type="getUserInfo" bindtap="getUserProfile" class="userLogin">
        點(diǎn)擊登錄
    </button>
    <button open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">獲取用戶手機(jī)號(hào)</button>
</view>

wxss:

.banner {
  border-radius: 10rpx;
  border: none;
  box-sizing: content-box;
  padding: 20rpx 0;
  width: 90%;
  height: 370rpx;
  margin: 20rpx auto;
  background:linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%);
  /* background-image:image("../../images/cloudbg.jpg"); */
  text-align: center;
}

.topContainer {
  width: 100%;
  height: 260rpx;
  background-size: 100%;
  border-radius: 9px;
}
.userinfo-nickname {
  color:black;
}
.userLogin{
  width: 50%;
  box-sizing: none;
  font-size: medium;
}
.userinfo-avatar {
  width: 150rpx;
  height: 150rpx;
  margin-bottom: 10rpx;
  border-radius: 50%;
}

js:

Page({
  data: {
         //用戶基本信息(頭像、昵稱)
         userinfo: {
             avatarUrl:'../../images/ckbg1.png',
             nickName:'未授權(quán)'
         },
         //是否已經(jīng)獲取用戶信息
         hasUserInfo: false,
         //是否可以調(diào)用獲取信息得函數(shù)
         canIUseGetUserProfile: false,
         sessionkey:"",
         
     },
  //第一次獲取用戶信息
 getUserProfile : function(e){
         wx.getUserProfile({
           desc: '獲取您的微信個(gè)人信息',
           success:(res)=>{
               this.setData({
                 userinfo:res.userInfo,
                 hasUserInfo:true
               })
               wx.setStorageSync('userinfo', res.userInfo)
           },
           fail:function(e){
               wx.showToast({
                 title: '你選擇了取消',
                 icon: "none",
                 duration: 1500,
                 mask: true
               })
           }
         })
 },
  onLoad: function(n) {
     this.setData({
         canIUseGetUserProfile : true
     })
  
 },
 onShow: function() {
   var that = this;
         //獲取用戶的本地緩存數(shù)據(jù),userinfo信息是在用戶授權(quán)登錄時(shí)保存的
         var n = wx.getStorageSync("userinfo");
         //當(dāng)本地緩存的用戶名稱不為""或者null時(shí),設(shè)置userinfo信息
         if(n.nickName != '' && n.nickName != null){
             this.setData({
                 userinfo: n,
                 hasUserInfo:true,
                 canIUseGetUserProfile:true
             })
             // 通過wx.login獲取登錄憑證(code),然后通過code去獲取我們用戶的openid
             wx.login({
               success:(res)=>{
                   console.log(res);
                   that.getOpenId();
               },
             })
         }
 },
 
 getOpenId(){
   var that=this
  wx.login({
    success (res) {
      if (res.code) {
        wx.request({
          url: '       ',
          data: {
            code: res.code
          },
          method: 'get',
          header: {
            'content-type': 'application/json' //默認(rèn)值
          },
          success: function(res) { //res就是接收后臺(tái)返回的數(shù)據(jù)
            console.log(res.data);
            that.setData({
              sessionkey:res.data
            })
          },
        })
      } else {
        console.log('登錄失??!' + res.errMsg)
      }
    }
  })
 },
 getPhoneNumber(e) { 
   var that=this;
   console.log("手機(jī)號(hào):") 
   wx.request({
    url: '                   ',
    data: {
      sessionkey: that.data.sessionkey,
      iv:e.detail.iv,
      encryptedData:e.detail.encryptedData
    },
    method: 'get',
    header: {
      'content-type': 'application/json' //默認(rèn)值
    },
    success: function(res) { //res就是接收后臺(tái)返回的數(shù)據(jù)
      console.log(res.data);
    },
  })
 } 
 })

Java后臺(tái)文章來源地址http://www.zghlxwxcb.cn/news/detail-523313.html

 @RequestMapping("    ")                             //獲取sessinoid
    @ResponseBody
    public static void getOpenId(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String appId="                      ";
        String secret="                    ";
        String code=request.getParameter("code");
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        //這三個(gè)參數(shù)就是之后要填上自己的值。
        //替換appid,appsecret,和code
        String requestUrl = url;
        //調(diào)用get方法發(fā)起get請(qǐng)求,并把返回值賦值給returnvalue
        String  returnvalue=GET(requestUrl);
        System.out.println(requestUrl);//打印發(fā)起請(qǐng)求的url
        System.out.println(returnvalue);//打印調(diào)用GET方法返回值
        //定義一個(gè)json對(duì)象。
        JSONObject convertvalue=new JSONObject();

        //將得到的字符串轉(zhuǎn)換為json
        convertvalue=(JSONObject) JSON.parse(returnvalue);


        System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid
        System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,
        //把openid和sessionkey分別賦值給openid和sessionkey
        String openid=(String) convertvalue.get("openid");
        String sessionkey=(String) convertvalue.get("session_key");//定義兩個(gè)變量存儲(chǔ)得到的openid和session_key.
        Gson gson=new Gson();
        String json = gson.toJson(sessionkey);
        Writer out = response.getWriter();
        out.write(String.valueOf(json));
        out.flush();
    }
    //發(fā)起get請(qǐng)求的方法。
    public static String GET(String url) {
        System.out.println("start");//打印發(fā)起請(qǐng)求的url
        String result = "";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // 異常記錄
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e2) {
                // 異常記錄
            }
        }
        return result;
    }


    /**
     * 解密工具直接放進(jìn)去即可
     */
    @RequestMapping("decryptS5")                      //解密獲取手機(jī)號(hào)
    @ResponseBody
    public static String decryptS5(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sSrc=request.getParameter("encryptedData");
        String encodingFormat="utf-8";
        String sKey=request.getParameter("sessionkey");
        String ivParameter=request.getParameter("iv");
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            System.out.println(new String(original, encodingFormat));
            return new String(original, encodingFormat);
        } catch (Exception ex) {
            return null;
        }
    }

到了這里,關(guān)于微信小程序——獲取用戶手機(jī)號(hào)(Java后臺(tái))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包