• 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;
        }
    }

    //成功一定有方法,失败一定有原因。
  • 相关阅读:
    简单版购物车
    五级菜单
    九九乘法表及金字塔
    day02作业
    解决jar激活pycharm跳窗问题
    1
    第二周
    2019是前十年中最难的一年但极有可能是未来十年来最好的一年
    电脑必备软件之让电脑桌面简洁帅气
    补码一位乘法(五位小数)
  • 原文地址:https://www.cnblogs.com/webapi/p/15602530.html
Copyright © 2020-2023  润新知