備忘錄:C#獲取微信小程式的雲資料庫中資料

shanzm發表於2021-08-30

shanzm-2021年8月17日 21:14:24

0. 背景說明

試水小程式,實現訪客登記,現有.NET程式需要獲取該小程式的資料

0.2 獲取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.3 資料庫查詢

參考小程式文件: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.4 檔案下載

參考小程式文件:獲取檔案下載連結

傳送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. 參考文件

相關文章