preface:
Everyone may be very familiar with small programs. With the continuous popularity of small programs, more and more companies begin to promote and use them. Today, I received a demand to generate a small program code, and combine the promotion pictures given by the operation to make a beautiful promotion QR code. Scanning the QR code can enter the small program. In order to save the memory resources of the server, what I want is to successfully call the interface of generating applet code through wechat, directly convert the binary content of the picture returned by wechat (the returned picture Buffer) into a binary byte [] file stream, and then convert it into Image, so that there is no need to directly read the local background picture and draw the picture through GDI+(Graphics) after saving it locally. If you have any questions about the development of small programs, welcome to the comment area or qq private chat. I can study and explore together when I have time.
🚀 Back to the top
Select applet code generation method:
Firstly, the official wechat applet document provides three methods to generate applet codes, as shown below (this paper adopts the third business scenario, which requires a large number of codes):
Document details address: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
1. createwxaqrcode obtains the two-dimensional code of the applet, which is suitable for business scenarios that require a small number of codes. The applet code generated through this interface is permanently valid and has a quantity limit.
2. getwxacode obtains applet code, which is applicable to business scenarios that require a small number of codes. The applet code generated through this interface is permanently valid and has a quantity limit.
3. getwxacodeunlimit obtains the applet code, which is suitable for business scenarios with a large number of codes. The small program code generated through this interface is permanently valid, and the number is unlimited.
🚀 Back to the top
Get the applet's globally unique background interface call credentials (access_token):
Students who have developed wechat related businesses should know that access is required to call wechat interface in many cases_ The token interface calls the certificate. Generally speaking, access_ The valid duration of the token is 2 hours. In order to call the interface infrequently, we can save the calling credentials through the cache method and set a reasonable expiration time (redis, cookie and memory cache are very good choices).
Request address:
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
Request parameters:
Attribute type default value is required description
grant_type string is to fill in client_credential
appid string is the unique credential of the applet, that is, AppID, which can be obtained on the "wechat public platform - Settings - development settings" page. (you need to have become a developer and the account has no abnormal status)
secret string is the unique credential key of the applet, i.e. AppSecret. The acquisition method is the same as appid
Return value (JSON packet):
Attribute type description
access_token string the obtained certificate
expires_in number the effective time of the voucher, in seconds. The current value is within 7200 seconds.
errcode number error code
errmsg string error message
Request code:
Copy code
///
///Global access applet call (unique token)
///
///
public string GetWechatAccessToken()
{
var appId = "your applet AppID"// Applet unique credential, AppID
var secret = "your applet AppSecret"// Applet unique credential key, i.e. AppSecret
string Url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, secret);
string Result = HttpWebRequest(Url, "GET", "", Encoding.UTF8); var obj = JsonConvert.DeserializeObject<AccessToken>(Result); if (obj != null && obj.access_token != null) { return obj.access_token; } else { return ""; } } /// <summary> ///WebRequest network request /// </summary> ///< param name = "requesturl" > request address < / param > ///< param name = "method" > request method (GET/POST) < / param > ///< param name = "data" > request parameters (method="POST" needs to be carried) < / param > ///< param name = "encoding" > character encoding < / param > ///< param name = "contenttype" > content type of requested data < / param > /// <returns></returns> public string HttpWebRequest(string requestUrl, string method, string data, Encoding encoding,string contentType="application/json;charset=UTF-8") { WebRequest webRequest = WebRequest.Create(requestUrl); webRequest.Method = method; if (method == "POST") { byte[] bytes = Encoding.Default.GetBytes(data); webRequest.ContentType = contentType; webRequest.ContentLength = bytes.Length; Stream requestStream = webRequest.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } WebResponse response = webRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); if (responseStream == null) { return ""; } StreamReader streamReader = new StreamReader(responseStream, encoding); string result = streamReader.ReadToEnd(); responseStream.Close(); streamReader.Close(); return result; } /// <summary> ///Response model /// </summary> public class AccessToken { /// <summary> ///Obtained voucher /// </summary> public string access_token { get; set; } /// <summary> ///Valid time of voucher, unit: second. The current value is within 7200 seconds /// </summary> public int expires_in { get; set; } /// <summary> ///Error code /// </summary> public int errcode { get; set; } /// <summary> ///Error message /// </summary> public string errmsg { get; set; } }
Copy code
🚀 Back to the top
Applet code acquisition:
Request address:
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
Request parameters
Attribute type default value is required description
access_token string is the interface call credential
scene string is a maximum of 32 visible characters. It only supports numbers, upper and lower case English and some special characters:! #$& ' ()*+,/:;=?@-._~, Other characters should be encoded as legal characters by yourself (because% is not supported, Chinese cannot be processed with urlencode, please use other encoding methods)
page string whether the home page must be the page of the published applet (otherwise an error will be reported). For example, pages/index/index, do not fill in / before the root path and cannot carry parameters (please put the parameters in the scene field). If this field is not filled in, the home page will be skipped by default
width number 430 no width of QR code, unit Px, minimum 280px, maximum 1280px
auto_color boolean false No: automatically configure the line color. If the color is still black, it means that it is not recommended to configure the main tone. The default is false
line_color Object {"r": 0, "g": 0, "b": 0} no auto_ It takes effect when color is false, and rgb is used to set the color, for example, {"r": "xxx", "g": "xxx", "b": "xxx"} decimal representation
is_hyaline boolean false no whether a transparent background is required. When true, an applet with a transparent background is generated
Return value of successful request:
The returned picture Buffer (if the call is successful, the binary content of the picture (picture file stream) will be returned directly; if the request fails, the data in JSON format will be returned.)
Request exception return value:
Attribute type description
errcode number error code
errmsg string error message
Request code:
Note: This is different from the previous network request to obtain the authorization certificate because to receive the Image binary content (buffer) returned from the request, you need to convert the binary file stream into byte [] binary byte stream, and then convert the Image.
Copy code
///
///Get applet code picture
///
///Interface call credentials
///Carry parameters
private Image GetWetchatAppletQRCodeImage(string access_token, string param)
{
string requestData = "{"scene":"" + param + ""}";
string requestUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; byte[] payload = System.Text.Encoding.UTF8.GetBytes(requestData); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream();//Get the returned picture Buffer (file stream) byte[] imageBuffer = StreamToBytes(stream); return ByteArrayConvertToImage(imageBuffer); } /// <summary> ///Transfer file data into binary byte [] byte stream /// </summary> ///< param name = "stream" > file stream < / param > /// <returns></returns> private byte[] StreamToBytes(Stream stream) { List<byte> bytes = new List<byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } return bytes.ToArray(); } /// <summary> ///Convert byte [] to Iamge /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image ByteArrayConvertToImage(byte[] buffer) { using (MemoryStream ms = new MemoryStream(buffer)) { // Directly call the self-contained method in the Image library class and use the MemoryStream instance object to obtain the Image return Image.FromStream(ms); } }
Copy code
🚀 Back to the top
Merge applet and background code:
Copy code
///
///Applet promotion QR code acquisition
///
///User parameters carried by applet code
///
public JsonResult GetCompositePictureUrl(int userId)
{
//Picture storage physical path
var savePhysicalPath = HttpContext.Request.MapPath("~/qrcode/");
var imgBack = Image.FromFile(savePhysicalPath + "ewm.jpg");//Composite background picture var wechatQrcodeImg = GetWetchatAppletQRCodeImage(GetWechatAccessToken(),userId.ToString());//Get applet code picture var compositePictureUrl = CompositePicture(imgBack, wechatQrcodeImg, savePhysicalPath, 232, 719, 290, 290); return Json(new { code = 0, compositePictureUrl = compositePictureUrl }); } /// <summary> ///Composite picture /// </summary> ///< param name = "backgroundimage" > background image < / param > ///< param name = "qrcodeimg" > QR code picture < / param > ///< param name = "savephysicalpath" > physical path for storing pictures < / param > ///< param name = "xdeviation" > X-axis deviation of drawn image < / param > ///< param name = "ydeviation" > Y-axis deviation of drawn image < / param > ///< param name = "width" > Draw image width < / param > ///< param name = "height" > Draw image height < / param > /// <returns></returns> public string CompositePicture(Image backgroundImage, Image qrCodeImg, string savePhysicalPath, int xDeviation = 0, int yDeviation = 0, int width = 0, int height = 0) { Bitmap bitmap = new Bitmap(backgroundImage.Width, backgroundImage.Height); Graphics graphics = Graphics.FromImage(bitmap);//mapping graphics.Clear(Color.White); SolidBrush surush = new SolidBrush(Color.White); graphics.DrawImage(backgroundImage, 0, 0, backgroundImage.Width, backgroundImage.Height); graphics.DrawImage(qrCodeImg, xDeviation, yDeviation, width, height); GC.Collect();//Garbage cleaning string compositePictureUrl = savePhysicalPath + Guid.NewGuid().ToString() + ".jpg"; //Composite picture saving bitmap.Save(compositePictureUrl, System.Drawing.Imaging.ImageFormat.Jpeg); return compositePictureUrl; } USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
Amazon evaluation www.yisuping.com cn
Shenzhen website construction www.sz886.com com