实战
一:调用小程序接口获取二维码
/// <summary> /// 获取小程序二维码 /// </summary> /// <param name="param">二维码scene参数</param> /// <param name="width">二维码宽度</param> /// <returns></returns> public HttpResponseMessage QueryAppletQrCode(string param, int width) { HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK); if (param.IsEmpty()) { return result; } //获取小程序accesstoken var token= "";//方法省略 string jsonparam = ""; if (width > 0) { var data = new { scene = param, page = "pages/login/wxlogin", width = width }; jsonparam = data.ToJson(); } else { var data = new { scene = param, page = "pages/login/wxlogin" }; jsonparam = data.ToJson(); } var postdata = new StringContent(jsonparam); postdata.Headers.Clear(); postdata.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); HttpClient httpClient = new HttpClient() { BaseAddress= new Uri("https://api.weixin.qq.com/") }; var response=httpClient.PostAsync($"wxa/getwxacodeunlimit?access_token={token}",postdata).Result; return response; }
二:方法调用
MVC。这种方法 小程序image的src等于返回值即可
微信返回的是二进制内容,直接以二进制的方式读取即可。
/// <summary> /// 获取小程序图片 /// </summary> /// <param name="param"></param> /// <param name="width">宽度</param> /// <returns></returns> [HttpGet] public FileResult QueryAppletQrCode(string param, int width = 0) { var response = _orgBusiness.QueryAppletQrCode(param, width); var contentType = response.Content.Headers.ContentType?.ToString(); //二维码错误 if (!string.IsNullOrWhiteSpace(contentType) && contentType.Contains("json")) { var data = response.Content.ReadAsByteArrayAsync().Result; string path = Server.MapPath("/AppletImages/images/nore.png"); return File(path, @"image/PNG"); } else { var data = response.Content.ReadAsByteArrayAsync().Result; return File(data, @"image/JPEG"); } }
WebApi方式返回
注意把图片转成base64返回,不然小程序端获取有问题
/// <summary> /// 获取小程序图片 /// </summary> /// <param name="param">企业id</param> /// <param name="width">宽度</param> /// <returns></returns> [HttpGet] public HttpResponseMessage QueryAppletQrCode(string param, int width = 0) { var response = QueryAppletQrCode(param, width); var data = response.Content.ReadAsByteArrayAsync().Result; HttpResponseMessage returndata = new HttpResponseMessage(System.Net.HttpStatusCode.OK); returndata.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue (@"image/JPEG"); string strbaser64 = System.Convert.ToBase64String(data); returndata.Content =new StringContent(strbaser64); return returndata; }
小程序端base64显示
请发表评论