20171018 在小程序頁面去獲取用戶的OpenID


1. 在小程序的.js 文件中增加代碼

 1 //加載頁面時到后台服務去獲取openID
 2   onLoad: function (options) {
 3     //OpenId
 4     wx.login({
 5       //獲取code
 6       success: (res) => {
 7         wx.request({
 8           method: "GET",
 9           url: 'https://(自己的域名部分)/api/pc/GetOpenID', //僅為示例,並非真實的接口地址    
10           data: {
11             scode: res.code   // 使用wx.login得到的登陸憑證,用於換取openid
12           },
13           header: {
14             'content-type': 'application/json' // 默認值
15           },
16            success: (res) => {
17             this.setData({
18               sopenid: res.data
19             })
20             console.log(this.data.sopenid)
21            }
22         })
23         console.log(res.code) //這里只是為了在微信小程序客戶端好查看結果,找尋問題
24      }
25     })
26   },


2 . 服務器端Web API 通過小程序界面傳遞的數據去獲取 Open ID

 1   #region  --- 獲取OpenId ---
 2         [HttpGet]
 3         public string GetOpenID(string scode)
 4         {
 5             try
 6             {
 7 
 8                 var _APP_ID = "";   // 你申請的小程序ID
 9                 var _APP_SECRET = "";  // 小程序的SECRET ,當然這個是可微信公共平台去生成的
10 
11                 var url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", _APP_ID, _APP_SECRET, scode);
12                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
13                 request.Method = "Get";     // 這里是定義請求的方式
14 
15                 HttpWebResponse response = request.GetResponse() as HttpWebResponse;   //對請求返回的結果進行處理
16                 Stream io = response.GetResponseStream();
17                 StreamReader sr = new StreamReader(io, Encoding.UTF8);
18                 var html = sr.ReadToEnd();    //返回的內容被讀取為流
19                 sr.Close();
20                 io.Close();
21                 response.Close();
22 
23                 string key = "\"openid\":\"";
24                 int stratindex = html.IndexOf(key);   //截取字符
25 
26                 if (stratindex != -1)   //驗證是否存在OpenID ,有時使用過期的登陸憑證,會出現異常
27                 {
28                     int endindex = html.IndexOf("\"}", stratindex);    // 這里在截取字符時,要注意內容是否和截取的部分相同,否則截取會失敗
29                     string _openid = html.Substring(stratindex + key.Length, endindex - stratindex - key.Length);
30                     return _openid;
31                 }
32                 else {
33                     return "error";
34                 }
35               
36             }
37             catch (Exception ex)
38             {
39                 return "error"+ex;
40             }
41 
42 
43 
44         }
45         #endregion

 


免責聲明!

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



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