作者:采購員乙,來自原文地址
第一步 獲取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盤的圖片就是推廣二維碼,可以講服務器連接地址發給微信小程序,供微信小程序調用。
|