小友初學微信小程序開發,若是有些問題不對,請指出,謝謝html
我仍是來講一下個人學習之路吧!!!
web
源代碼連接 https://pan.baidu.com/s/1tjPtLvAh0tIpgQFE3w1fIQ 密碼:p4tl算法
1.在開發小程序的時候,咱們須要吧開發工具中的不校驗合法域名、web-view(業務域名)、TLS 版本以及 HTTPS 證書這個給打開,由於咱們在微信公衆平臺申請成爲小程序開發者時須要設置一個叫作合法服務器域名的東西,每當咱們請求服務器的時候,它都會驗證咱們請求的服務器是否是合法的(也就是咱們設置的服務器地址)sql
設置的合法服務器域名的地方 : 登入微信公衆平臺--->設置--->開發設置 (若是開發完了,上線的話,就能夠設置這裏)json
關閉驗證的地方:打開小程序開發工具--->點擊右上角的詳情按鈕--->最後有一個選項給打開 (通常咱們在開發測試的時候最好打開,這樣便於開發)小程序
2.由於我是學習因此我打開了此選項-----如今咱們須要配置IIS(如今電腦基本自帶了,沒有的也能夠去下載)c#
這個是配置電腦的IISwindows
若是這樣就能夠了,就錯了,咱們還須要在執行一些dism命令(按照順序一步一步執行)原文地址微信小程序
dism /online /enable-feature /featurename:IIS-ISAPIFilter dism /online /enable-feature /featurename:IIS-ISAPIExtensions dism /online /enable-feature /featurename:IIS-NetFxExtensibility45 dism /online /enable-feature /featurename:IIS-ASPNET45 c:\windows\microsoft.net\framework64\v4.0.30319\aspnet_regiis.exe -i
3.這所有弄完後,咱們如今就能夠開始實現咱們第一個微信小程序了api
1)若是咱們只是獲取用戶的一些基本信息(例如 暱稱 頭像等),不包括敏感信息(例如openid)
小程序代碼以下:
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo);
console.log(res.userInfo.nickName);
console.log(res.userInfo.avatarUrl);
},
})
文檔說明:
爲優化用戶體驗,使用 wx.getUserInfo 接口直接彈出受權框的開發方式將逐步再也不支持。從2018年4月30日開始,小程序與小遊戲的體驗版、開發版調用 wx.getUserInfo 接口,將沒法彈出受權詢問框,默認調用失敗。正式版暫不受影響。開發者可以使用如下方式獲取或展現用戶信息: 詳細連接
改進後的小程序代碼:
wxml
<button open-type="getUserInfo" id='btnInner' type='primary' lang="zh_CN" bindgetuserinfo="onGotUserInfo">進入小程序</button>
js
onGotUserInfo: function (e) {
console.log(e);
console.log(e.detail);
console.log(e.detail.rawData);
console.log(e.detail.userInfo);
}
效果:
4.獲取用戶的敏感信息(關於網絡請求的開發文檔)
代碼以下:
wxml
<button open-type="getUserInfo" id='btnInner' type='primary' lang="zh_CN" bindgetuserinfo="onGotUserInfo">進入小程序</button>
js
onGotUserInfo: function (e) { wx.login({ success: function (logRes) { if (e.detail.errMsg) { wx.request({ url: 'http://localhost:80/handlers/WxAjaxHandler.ashx', data: { funType: "AES_decrypt", iv: e.detail.iv,//偏移向量 code: logRes.code,//微信登入憑證-----方便後臺用code和本身的appid換取session_key(密鑰) encryptedData: e.detail.encryptedData//密文 }, header: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" }, method: 'post', dataType: 'json', responseType: 'text', success: function (res) { console.log(res.data); }, }) } }, }) }
c#後臺代碼以下:
using MyCommon; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace WebApplication5.handlers { /// <summary> /// WxAjaxHandler 的摘要說明 /// </summary> public class WxAjaxHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string strReturn = ""; string funType = context.Request["funType"]; if ("AES_decrypt".Equals(funType)) { string iv = context.Request["iv"]; string code = context.Request["code"]; string encryptedData = context.Request["encryptedData"]; AES aes = new AES(); strReturn = aes.AESDecrypt(code, iv, encryptedData); } context.Response.Write(strReturn); } public bool IsReusable { get { return false; } } } }
AES解密代碼以下:查看本身的appid和AppSecret的地方:登入微信公衆平臺--->設置--->開發設置
using Models; using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; namespace MyCommon { public class AES:System.Web.UI.Page { private const string appid = "appid";//本身的appid private const string appsecret = "appsecret";//本身的小程序的密鑰appsecret /// <summary> /// 1.對稱解密使用的算法爲 AES-128-CBC,數據採用PKCS#7填充。 /// 2.對稱解密的目標密文爲 Base64_Decode(encryptedData)。 /// 3.對稱解密祕鑰 aeskey = Base64_Decode(session_key), aeskey 是16字節。 /// 4.對稱解密算法初始向量 爲Base64_Decode(iv),其中iv由數據接口返回。 /// </summary> /// <param name="code">登入憑證</param> /// <param name="iv">偏移向量</param> /// <param name="encryptedDataStr">要被解碼的敏感數據源</param> /// <returns></returns> public string AESDecrypt(string code, string iv, string encryptedDataStr) { try { string key = GetStrKeyByCode(code); WxModel jsonKey = JsonConvert.DeserializeObject<WxModel>(key); key = jsonKey.session_key; RijndaelManaged rijalg = new RijndaelManaged(); //設置 cipher 格式 AES-128-CBC rijalg.KeySize = 128; rijalg.Padding = PaddingMode.PKCS7; rijalg.Mode = CipherMode.CBC; rijalg.Key = Convert.FromBase64String(key); rijalg.IV = Convert.FromBase64String(iv); byte[] encryptedData = Convert.FromBase64String(encryptedDataStr); //解密 ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV); string result; using (MemoryStream msDecrypt = new MemoryStream(encryptedData)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { result = srDecrypt.ReadToEnd(); } } } return result; } catch (Exception ex) { new Exception(ex.Message); return null; } } /// <summary> /// 根據微信登入憑證和本身的appid,來獲取用戶的密鑰session_key /// </summary> /// <param name="code">登入憑證</param> /// <returns>一個json格式的字符串</returns> protected string GetStrKeyByCode(string code) { string responseContent = string.Empty; string reqUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&js_code={1}&secret={2}&grant_type=authorization_code"; string url = string.Format(reqUrl, appid, code, appsecret); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "GET"; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; using (WebResponse webRes = req.GetResponse()) { using (StreamReader sr = new StreamReader(webRes.GetResponseStream(), Encoding.Default)) { responseContent = sr.ReadToEnd().ToString(); } } return responseContent; } } }
model
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Models { public class WxModel { public string opendid { get; set; } public string session_key { get; set; } } }
返回效果以下:
返回的信息列表
{ "openId": "OPENID", "nickName": "NICKNAME", "gender": GENDER, "city": "CITY", "province": "PROVINCE", "country": "COUNTRY", "avatarUrl": "AVATARURL", "unionId": "UNIONID", "watermark": { "appid":"APPID", "timestamp":TIMESTAMP } }
連接:https://pan.baidu.com/s/1tjPtLvAh0tIpgQFE3w1fIQ 密碼:p4tl