作者:采购员乙,来自原文地址
第一步 获取access_token:
文档如下:
http请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
代码如下:
string result = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx***********d&secret=a*******************4");
public static string HttpGet(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
其中****改成自己的。具体到微信公众平台小程序里设置开发设置里找。
第二步 获取推广二维码
文档:
https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN POST 参数说明
参数 默认值 说明 path 不能为空,最大长度 128 字节 width 430 二维码的宽度 代码:
public static void PostMoths(string access_token)
{
string _url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + access_token;
string strURL = _url;
System.NET.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
JsonData _data = new JsonData();
_data["path"] = "pages/index?query=1";
_data["width"] = "430";
string _jso = _data.ToJson();
//string paraUrlCoded = param;
byte[] payload;
//payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
payload = System.Text.Encoding.UTF8.GetBytes(_jso);
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 s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
byte[] tt = StreamToBytes(s);
//将流保存在c盘test.png文件下
System.IO.File.WriteAllBytes(@"d:\test.png", tt);
}
///将数据流转为byte[]
public static 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();
}
最后保存在d盘的图片就是推广二维码,可以讲服务器连接地址发给微信小程序,供微信小程序调用。