C#獲取微信小程序的雲數據庫中數據的示例代碼

0 背景說明

試水小程序,實現訪客登記,現有.NET程序需要獲取該小程序的數據

0.1 獲取AccessToken

調用絕大多數後臺接口時都需使用 access_token

參考小程序文檔:auth.getAccessToken

發送Get請求,獲取AccessToken

接口:

  • https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

參數:

  • appid:小程序ID
  • secret:註冊時產生的密鑰,可以重置
  • 兩個參數信息可以在後臺->開發管理->開發設置->開發者設置中查看

返回值:

格式如下:

    {"access_token":"ACCESS_TOKEN","expires_in":7200}

  • access_token:獲取到的憑證
  • expires_in:憑證的有效時間,單位:秒

0.2 數據庫查詢

參考小程序文檔:databaseQuery

發送Post請求,獲取數據

接口:

  • POST https://api.weixin.qq.com/tcb/databasequery?access_token=ACCESS_TOKEN

參數:

接口地址中加入AccessToken

請求參數:

  • env:雲環境ID
  • query:數據庫操作語句

格式如下:

{ "env":"小程序環境", "query": "db.collection(\"集合名稱\").where({done:true}).limit(10).skip(1).get()" }

query中應使用limit()限制單次拉取的數量,默認10條。

0.3 文件下載

參考小程序文檔:獲取文件下載鏈接

發送post請求獲取

接口:

  • POST https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=ACCESS_TOKEN

參數:

  • 接口地址中加入AccessToken

請求參數:

  • env:雲環境ID
  • file_list:文件列表

格式如下:

{ "env": "雲環境ID", "file_list": [ { "fileid":"文件ID", "max_age":7200 } ] }

2. 簡單的封裝

簡單的封裝瞭發送請求的方法

//需要添加的命名空間
using Newtonsoft.Json;
using System.IO;

/// <summary>
/// 發送http Get請求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static HttpWebResponse GetRequest(string url)
{
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";//鏈接類型
    return request.GetResponse() as HttpWebResponse;
}

/// <summary>
/// 發送http Post請求
/// </summary>
/// <returns></returns>
public static HttpWebResponse PostRequest(string url, string messsage)
{
    byte[] byteData = Encoding.UTF8.GetBytes(messsage);
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/json;charset=UTF-8";
    webRequest.ContentLength = byteData.Length;
    using (Stream stream = webRequest.GetRequestStream())
    {
        stream.Write(byteData, 0, byteData.Length);
    }
    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
    return response;
}

/// <summary>
/// 從HttpWebResponse對象中提取響應的數據轉換為字符串
/// </summary>
/// <param name="webresponse"></param>
/// <returns></returns>
public static string HttpWebResponseToString(HttpWebResponse webresponse)
{
    using (Stream s = webresponse.GetResponseStream())
    {
        StreamReader reader = new StreamReader(s, Encoding.UTF8);
        return reader.ReadToEnd();
    }
}

/// <summary>
/// Json字符串轉為匿名對象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <param name="anonymousTypeObject"></param>
/// <returns></returns>
public static T DesAnonymousType<T>(string json, T anonymousTypeObject)
{
    return JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
}

3. 簡單測試

發送請求獲取數據

/// <summary>
/// 獲取access_token
/// </summary>
/// <returns></returns>
public static string GetAccessToken()
{
    // 通過Get請求獲取access_token
    HttpWebResponse httpWebResponse = GetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credentiaappid=小程序ID&secret=小程序密鑰");
    string resultJson = HttpWebResponseToString(httpWebResponse);
    var resultObj = DesAnonymousType(resultJson, new { access_token = "", expires_in = "" });
    return resultObj.access_token;
}

/// <summary>
///  查詢數據
/// </summary>
/// <param name="queryString">形如: $"{{\"env\":\"小程序環境id\", \"query\": \"db.collecti(\\\"數據集合名稱\\\").where({{集合中字段:\\\"集合中字段值\\\"}}).limit(10).get()\"}}"</param>
/// <returns></returns>
public static string GetData(string queryString)
{
    string accessToken = GetAccessToken();
    HttpWebResponse httpWebResponse = PostRequest("https://api.weixin.qq.com/tcb/databasequery?access_token=" + accessTokenqueryString);
    string data = HttpWebResponseToString(httpWebResponse);
    return data;
}


/// <summary>
/// 通過FileId獲取文件下載URL
/// </summary>
/// <param name="queryString">形如:$"{{\"env\": \"環境ID\",\"file_list\": [{{\"fileid\":文件ID\",\"max_age\":7200 }}]}}"</param>
/// <returns></returns>
public static string GetDownFileUrl(string queryString)
{
    string accessToken = GetAccessToken();
    string url = $"https://api.weixin.qq.com/tcb/batchdownloadfile?access_token={accessToken}";
    HttpWebResponse httpWebResponse = PostRequest(url, queryString);
    string downFileUrl = HttpWebResponseToString(httpWebResponse);
    return downFileUrl;
}

4. 參考文檔

小程序官方文檔:雲開發->數據庫查詢記錄

小程序官方文檔:接口調用憑證->getAccessToken

到此這篇關於C#獲取微信小程序的雲數據庫中數據的示例代碼的文章就介紹到這瞭,更多相關C#獲取小程序數據內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: