业务系统——C#获取微信小程序的云数据库中数据

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. 参考文档

posted @ 2021-08-30 22:08  shanzm  阅读(1287)  评论(0编辑  收藏  举报
TOP