zoukankan      html  css  js  c++  java
  • asp.net生成微信小程序二维码

    asp.net生成微信小程序二维码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    using System.Net;
    using Newtonsoft.Json.Linq;
    
    /// <summary>
    ///微信小程序
    /// </summary>
    public class wxapp
    {
        //pages/login/login?key=
        /// <summary>
        /// 获取access_token        
        /// </summary>        
        /// <returns></returns>        
        public static string GetAccessToken(string AppID, string AppSecret)
        {
            string token = string.Empty;
            try
            {
                string url = "http://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret;
                WebClient wc = new WebClient();
                string result = wc.DownloadString(url);
                if (!string.IsNullOrWhiteSpace(result))
                {
                    var jObject = JObject.Parse(result);
                    token = jObject["access_token"].ToString();
                }
                return token;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
    
        /// <summary>
        /// 获取小程序二维码
        /// </summary>
        /// <param name="AppID">小程序AppID</param>
        /// <param name="AppSecret">小程序AppSecret</param>
        /// <param name="page">小程序页面,格式:pages/index/index?id=1</param>
        /// <param name="dir">二维码保存目录,格式:/upload/</param>
        /// <returns>二维码网址</returns>
        public static string Getqrcode(string AppID, string AppSecret, string page, string dir)
        {
            //只能生成10万个
            //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
            //var page = "pages/index/index?id=1";
            string token = GetAccessToken(AppID, AppSecret);
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    //var url = string.Format("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={0}", token);
                    var url = string.Format("https://api.weixin.qq.com/wxa/getwxacode?access_token={0}", token);         
                    var DataJson = "{";
                    //DataJson += string.Format("\"width\":\"{0}\",", "430");//大小,最小280px,最大1280px,默认430
                    DataJson += string.Format("\"path\":\"{0}\"", page);//小程序地址,根路径前不要填加'/',最大128字节
                    DataJson += "}";
                    System.Net.HttpWebRequest request;
                    request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST";
                    request.ContentType = "application/json;charset=UTF-8";
                    byte[] payload;
                    payload = System.Text.Encoding.UTF8.GetBytes(DataJson);
                    request.ContentLength = payload.Length;
                    Stream writer = request.GetRequestStream();
                    writer.Write(payload, 0, payload.Length);
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.Stream stream;
                    stream = response.GetResponseStream();
    
                    List<byte> bytes = new List<byte>();
                    int temp = stream.ReadByte();
                    while (temp != -1)
                    {
                        bytes.Add((byte)temp);
                        temp = stream.ReadByte();
                    }
                    byte[] result = bytes.ToArray();
    
                    String dirPath = HttpContext.Current.Server.MapPath(dir);
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
                    string filePath = dirPath + fileName;
                    FileStream fs = new FileStream(filePath, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(result, 0, result.Length);
                    bw.Close();
                    fs.Close();
                    return dir + fileName;
                }
                catch { }
            }
            return string.Empty;
        }
        public static string Getqrcode2(string AppID, string AppSecret, string page, string dir)
        {
            //只能生成10万个
            //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
            //var page = "pages/index/index?id=1";
            string token = GetAccessToken(AppID, AppSecret);
            if (!string.IsNullOrEmpty(token))
            {
                //try
                //{
                    var url = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", token);
                    var DataJson = "{";
                    //DataJson += string.Format("\"width\":\"{0}\",", "430");//大小,最小280px,最大1280px,默认430
                    DataJson += string.Format("\"scene\":\"{0}\",", "key=a-b-cv");
                    DataJson += string.Format("\"check_path\":\"{0}\",", "false");
                    DataJson += string.Format("\"page\":\"{0}\"", page);//小程序地址,根路径前不要填加'/',最大128字节
                    
                    DataJson += "}";
                    System.Net.HttpWebRequest request;
                    request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                    request.Method = "POST";
                    request.ContentType = "application/json;charset=UTF-8";
                    byte[] payload;
                    payload = System.Text.Encoding.UTF8.GetBytes(DataJson);
                    request.ContentLength = payload.Length;
                    Stream writer = request.GetRequestStream();
                    writer.Write(payload, 0, payload.Length);
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.Stream stream;
                    stream = response.GetResponseStream();
    
                    List<byte> bytes = new List<byte>();
                    int temp = stream.ReadByte();
                    while (temp != -1)
                    {
                        bytes.Add((byte)temp);
                        temp = stream.ReadByte();
                    }
                    byte[] result = bytes.ToArray();
    
                    String dirPath = HttpContext.Current.Server.MapPath(dir);
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
                    string filePath = dirPath + fileName;
                    FileStream fs = new FileStream(filePath, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(result, 0, result.Length);
                    bw.Close();
                    fs.Close();
                    return dir + fileName;
                //}
                //catch { }
            }
            return string.Empty;
        }
    }

    //成功一定有方法,失败一定有原因。
  • 相关阅读:
    2-7.交集选择器
    2-6.并集选择器
    2-5.后代选择器
    python----字符串,反向编码与乱码记录
    python----输出1-100之和的方法
    python----基础之三元运算、文件操作
    python----基础之令人头疼的字符编码
    python----基础之可变、不可变数据类型、collections模块
    python----基础之数据类型(元祖,字典,集合)
    python----基础之变量的创建与id
  • 原文地址:https://www.cnblogs.com/webapi/p/15602530.html
Copyright © 2011-2022 走看看