public static void CreateQRCode()
{
string token = GetAccessToken();
CreatewxaQRCodeModel qrcodeModel = new CreatewxaQRCodeModel
{
path = "pages/home-page/main?scene=29f60878c7dc5061"
};
//微信请求小程序码的url
string url = "http://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + token;
string json = JsonConvert.SerializeObject(qrcodeModel);
DownFile(url, "C:\\1.png", json);
}
private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
//为了通过证书验证,总是返回true
return true;
}
/// <summary>
///
/// </summary>
/// <param name="url">地址</param>
/// <returns></returns>
public static string Get(string url)
{
string data = string.Empty;
using (var client = new HttpClient())
{
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, url);

ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
var result = client.SendAsync(msg).Result;

var content = result.Content.ReadAsStringAsync();
data = content.Result;
}
return data;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="url">地址</param>
/// <param name="localFileName">保存地址</param>
/// <param name="json">参数</param>
/// <returns></returns>
public static void DownFile(string url, string localFileName, string json)
{
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
// 发起请求并异步等待结果
using (var httpClient = new HttpClient())
{
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, url);
msg.Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json");


ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
var responseMessage = httpClient.SendAsync(msg).Result;
if (responseMessage.IsSuccessStatusCode)
{
using (var fs = File.Create(localFileName))
{
// 获取结果,并转成 stream 保存到本地。
var streamFromService = responseMessage.Content.ReadAsStreamAsync().Result;
streamFromService.CopyTo(fs);
}
}
}
}

/// <summary>
/// 获取access_token
/// </summary>
/// <returns></returns>
public static string GetAccessToken()
{
string token = string.Empty;
string appid = "*";
string secret = "*";
try
{
var result = Get("http://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" +
secret);
if (!string.IsNullOrWhiteSpace(result))
{
var jObject = JObject.Parse(result);
token = jObject["access_token"].ToString();
}
return token;
}
catch (Exception ex)
{
return "";
}
}
public class CreatewxaQRCodeModel
{
public string path { get; set; }
}