項目介紹
1、微信小程序獲取openid和session_key
2、后台使用C#開發
項目流程
准備工作
1 獲取appid
1.1 下載微信web開發工具
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
1.2 安裝完成后打開
1.2.1 新建項目
1.2.2 點擊測試號,點擊新建。項目創建成功
測試號功能有限但是對於簡單使用已經足夠,應用開發可以注冊一個AppID
2 獲取appsecret
小程序端
1 小程序端官方API訪問地址
https://developers.weixin.qq.com/miniprogram/dev/
2 小程序端向服務器發起請求,參數是code
// 登錄
wx.login({
success: res => {
console.log("getUserremark:"+res.code);
wx.request({
url: 'http://localhost:7655/WebService.asmx/GetCode?json_code='+res.code,
data: {
'json_code': res.code
},
method: 'GET',
header: {
'content-type': 'appication/x-www-form-urlencoded'
},
success: function (res) {
console.log("back Data:"+res.data.data);
}
})
// 發送 res.code 到后台換取 openId, sessionKey, unionId
}
})
3 url說明
訪問后台服務器,將code值傳遞給服務,並進行調用
后端
這里提供的方法僅供參考,其他語言,其他方法均可用
1 Visual Studio新建website項目
2 右擊website,添加服務
3 在WebService.cs的public WebService()下添加如下代碼
#region 獲取小程序openid 和session_key
[WebMethod] //網頁中顯示這個方法
public void GetCode(string json_code)
{
string serviceAddress =
"https://api.weixin.qq.com/sns/jscode2session?appid=自己的&secret=自己的"
+ "&js_code=" + json_code + "&grant_type=authorization_code";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "GET";
request.ContentType = "text/html;charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
var obj = new
{
data = retString,
Success = true
};
Formatting microsoftDataFormatSetting = default(Formatting);
string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSetting);
HttpContext.Current.Response.Write(result);
}
#endregion
4 程序調用需要用到庫,下載地址
鏈接:https://pan.baidu.com/s/1Lfldi6EouII9F_3eeD7HnA
提取碼:r8uf
鏈接無效可以自己在網上找,或聯系我
5 部署服務,網頁界面如下
程序調試
1 網頁中打開服務
2 點擊GetCode,跳轉到如下界面
3 獲取js_code(用戶登陸憑證)
4 復制用戶登陸憑證,並填入到服務中,並調用
如果返回結果正確說明服務器端無問題
備注:小程序接收的數據需要時json格式的