GVKun编程网logo

微信大众平台接口(微信大众平台接口是什么)

12

如果您对微信大众平台接口感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于微信大众平台接口的详细内容,我们还将为您解答微信大众平台接口是什么的相关问题,并且为您提供关于.net

如果您对微信大众平台接口感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于微信大众平台接口的详细内容,我们还将为您解答微信大众平台接口是什么的相关问题,并且为您提供关于.net 后台以post方式调用微信公众平台接口、C#-微信公众平台接口-上传临时素材、C#版微信公众平台接口调用源码打包下载、java 调用微信公众平台接口(二)的有价值信息。

本文目录一览:

微信大众平台接口(微信大众平台接口是什么)

微信大众平台接口(微信大众平台接口是什么)

微信公众平台接口

<?php <br />
/**<br>
  * wechat php test<br>
  */<br><br>
//define your token<br>
define("TOKEN", "qianshou");<br>
$wechatObj = new wechatCallbackapiTest();<br>
$wechatObj-&gt;valid();<br>
$wechatObj-&gt;responseMsg();<br><br>
class wechatCallbackapiTest<br>
{<br>
	public function valid()<br>
    {<br>
        $echoStr = $_GET["echostr"];<br><br>
        //valid signature , option<br>
        if($this-&gt;checkSignature()){<br>
        	echo $echoStr;<br>
        	exit;<br>
        }<br>
    }<br><br>
    public function responseMsg()<br>
    {<br>
		//get post data, May be due to the different environments<br>
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];<br><br>
      	//extract post data<br>
		if (!empty($postStr)){<br>
                <br>
              	$postObj = simplexml_load_string($postStr, ''SimpleXMLElement'', LIBXML_NOCDATA);<br>
                $fromUsername = $postObj-&gt;FromUserName;<br>
                $toUsername = $postObj-&gt;ToUserName;<br>
                $keyword = trim($postObj-&gt;Content);<br>
                $time = time();<br>
                $textTpl = "<xml><br><tousername></tousername><br><fromusername></fromusername><br><createtime>%s</createtime><br><msgtype></msgtype><br><content></content><br><funcflag>0</funcflag><br></xml>";             <br>
				if(!empty( $keyword ))<br>
                {<br>
              		$msgType = "text";<br>
                	$contentStr = "Welcome to wechat world!";<br>
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br>
                	echo $resultStr;<br>
                }else{<br>
                	echo "Input something...";<br>
                }<br><br>
        }else {<br>
        	echo "qianshouerror"; <div></div>
登录后复制

.net 后台以post方式调用微信公众平台接口

.net 后台以post方式调用微信公众平台接口

1 public class Fresult
2 {
3         public int errcode { get; set; }
4         public string errmsg { get; set; }
5         public string msgid { get; set; }
6 }
 1  public static Fresult SendTemplateMessage(string accessToken, string body)
 2 {
 3             Fresult fresult = new Fresult();
 4             string uriStr = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={accessToken}";
 5             var uri = new Uri(uriStr);
 6             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
 7             request.Method = "POST";
 8             request.ContentType = "application/json";
 9             request.Accept = "application/json";
10             Encoding encoding = Encoding.UTF8;
11             byte[] data = encoding.GetBytes(body);
12             Stream sm = request.GetRequestStream();
13             sm.Write(data, 0, data.Length);
14             sm.Close();
15             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
16             using (Stream streamResponse = response.GetResponseStream())
17             {
18                 using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
19                 {
20                     char[] readBuff = new char[256];
21                     int count = streamRead.Read(readBuff, 0, 256);
22                     string content = "";
23                     while (count > 0)
24                     {
25                         string outputData = new string(readBuff, 0, count);
26                         content += outputData;                                             
27                         count = streamRead.Read(readBuff, 0, 256);
28                     }
29                     fresult = JsonConvert.DeserializeObject<Fresult>(content);
30                 }
31             }
32             response.Close();
33             response.Dispose();
34             return fresult;
35 }

 

C#-微信公众平台接口-上传临时素材

C#-微信公众平台接口-上传临时素材

转:http://blog.niunan.net/blog/show/1212

最烦做微信公众平台的东西。。文档说得不清不楚,又没示例代码,只能自己 慢慢搜索,弄了一晚上,基本弄出来了,把本地的图片上传到微信的临时素材那里,返回媒体ID,用于其他操作,代码如下 :(自己导入相应的类System.Net.Http,JSON解析用的LitJson)

       /// <summary>
        /// 上传临时素材
        /// 返回media_id
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string UploadLinShiSuCai(int userid) {
            string imgpath = HttpContext.Current.Server.MapPath($"/upload/erweima/{userid}_2.png");
            string appid = WxPayConfig.APPID;
            string secret = WxPayConfig.APPSECRET;

            //1. 获取Accesstoken(有效期7200秒,开发者必须在自己的服务全局缓存access_token)
            string url1 = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
            string result = HttpService.Get(url1);
            JsonData jd = JsonMapper.ToObject(result);
            string access_token = (string)jd["access_token"];

            string url2 = $"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image";

            //图片转为流
            Image img = new Bitmap(imgpath);
            MemoryStream stream = new MemoryStream();
            img.Save(stream,ImageFormat.Png);
            BinaryReader br = new BinaryReader(stream);
            byte[] data = stream.ToArray();
            stream.Close();



            var boundary = "fbce142e-4e8e-4bf3-826d-cc3cf506cccc";
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("User-Agent","KNowledgeCenter");
            client.DefaultRequestHeaders.Remove("Expect");
            client.DefaultRequestHeaders.Remove("Connection");
            client.DefaultRequestHeaders.ExpectContinue = false;
            client.DefaultRequestHeaders.ConnectionClose = true;
            var content = new MultipartFormDataContent(boundary);
            content.Headers.Remove("Content-Type");
            content.Headers.TryAddWithoutValidation("Content-Type","multipart/form-data; boundary=" + boundary);
            var contentByte = new ByteArrayContent(data);
            content.Add(contentByte);
            contentByte.Headers.Remove("Content-disposition");
            contentByte.Headers.TryAddWithoutValidation("Content-disposition",$"form-data; name=\"media\";filename=\"{userid}_2.png\"" + "");
            contentByte.Headers.Remove("Content-Type");
            contentByte.Headers.TryAddWithoutValidation("Content-Type","image/png");
            try
            {
                var result2 = client.PostAsync(url2,content);
                if (result2.Result.StatusCode != HttpStatusCode.OK)
                    throw new Exception(result2.Result.Content.ReadAsstringAsync().Result);
                string jsonstr = result2.Result.Content.ReadAsstringAsync().Result;
                JsonData jd2 = JsonMapper.ToObject(jsonstr);
                result = (string)jd2["media_id"];
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.InnerException.Message);
            } 

        }
ASP.NET

C#版微信公众平台接口调用源码打包下载

C#版微信公众平台接口调用源码打包下载

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Net;


public partial class weixin : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        string weixin1 = "";
        weixin1 += "{\n";
        weixin1 += "\"button\":[\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"今日歌曲\",\n";
        weixin1 += "\"key\":\"V1001_TODAY_MUSIC123eee\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"歌手简介\",\n";
        weixin1 += "\"key\":\"V1001_TODAY_SINGER123eee\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"name\":\"菜单\",\n";
        weixin1 += "\"sub_button\":[\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"hello word\",\n";
        weixin1 += "\"key\":\"V1001_HELLO_WORLD123eee\"\n";
        weixin1 += "},\n";
        weixin1 += "{\n";
        weixin1 += "\"type\":\"click\",\n";
        weixin1 += "\"name\":\"赞一下我们\",\n";
        weixin1 += "\"key\":\"V1001_GOOD123eee\"\n";
        weixin1 += "}]\n";
        weixin1 += "}]\n";
        weixin1 += "}\n";
        string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=你自己的token", weixin1);

    }
    public string GetPage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }
}

 

java 调用微信公众平台接口(二)

java 调用微信公众平台接口(二)

接着上一个随笔,分享了上传素材,这一个分享获取永久素材

1、获取单个图文素材

如果需要将示例放入集合,需要实体类

/*获取素材列表参数实体类**/
public class Material {
    
    private String title;//图文消息的标题
    private String thumb_media_id;//图文消息的封面图片素材id(必须是永久mediaID)
    private String author;//作者
    private String digest;//图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
    private String content;//图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
    private String url;//图文页的URL,或者,当获取的列表是图片素材列表时,该字段是图片的URL
    private Integer show_cover_pic;//是否显示封面,0为false,即不显示,1为true,即显示
    private String content_source_url;//图文消息的原文地址,即点击“阅读原文”后的URL
    private Integer need_open_comment;//Uint32 是否打开评论,0不打开,1打开
    private Integer only_fans_can_comment;//Uint32 是否打开评论,0不打开,1打开L
    
    public Integer getNeed_open_comment() {
        return need_open_comment;
    }
    public void setNeed_open_comment(Integer need_open_comment) {
        this.need_open_comment = need_open_comment;
    }
    public Integer getOnly_fans_can_comment() {
        return only_fans_can_comment;
    }
    public void setOnly_fans_can_comment(Integer only_fans_can_comment) {
        this.only_fans_can_comment = only_fans_can_comment;
    }
    public String getContent_source_url() {
        return content_source_url;
    }
    public void setContent_source_url(String content_source_url) {
        this.content_source_url = content_source_url;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getThumb_media_id() {
        return thumb_media_id;
    }
    public void setThumb_media_id(String thumb_media_id) {
        this.thumb_media_id = thumb_media_id;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getDigest() {
        return digest;
    }
    public void setDigest(String digest) {
        this.digest = digest;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public int getShow_cover_pic() {
        return show_cover_pic;
    }
    public void setShow_cover_pic(int show_cover_pic) {
        this.show_cover_pic = show_cover_pic;
    }
    
}

 调用方法

public final static String MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";

 /**
     * 获取素材单个
     * @param accessToken 获取接口凭证的唯一标识
     * @param type 素材的类型,图片(image)、视频(video)、语音 (voice)
     * @param offset 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
     * @param count 返回素材的数量,取值在1到20之间
     * @return
     */
    public static List<Material> getMaterial(String accessToken,String meidaId) { 
        List<Material> lists = new ArrayList<Material>();//定义图文素材实体类集合
        String outputStr="";//定义一个空的参数字符串
        String requestUrl = MATERIAL.replace("ACCESS_TOKEN", accessToken);//替换调access_token
        MesByOpenIdParam para = new MesByOpenIdParam();//调用接口所需要的参数实体类
        Mpnews mpnews = para.new Mpnews();
        //mpnews.setMedia_id("kjqT60HOZg-aS6TuPriow1o1JRYgMZJlte66ytQS14U");
        mpnews.setMedia_id(meidaId);
        JSONObject jsonObject = new JSONObject();
        jsonObject = JSONObject.fromObject(mpnews);
        outputStr = jsonObject.toString();//将参数对象转换成json字符串
        
        jsonObject = httpsRequest(requestUrl, "POST", outputStr);  //发送https请求(请求的路径,方式,所携带的参数)
        // 如果请求成功  
        if (null != jsonObject) {
            try {  
                JSONArray jsonArray = jsonObject.getJSONArray("news_item");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = (JSONObject) jsonArray.get(i);
                    System.out.println(json);
                    Material entity = new Material();
                    String title = json.getString("title");
                    String thumb_media_id = json.getString("thumb_media_id");
                    String str = json.getString("show_cover_pic");
                    Integer show_cover_pic = Integer.valueOf(str);
                    String author = json.getString("author");
                    String digest = json.getString("digest");
                    String content = json.getString("content");
                    String content_source_url = json.getString("content_source_url");
                    
                    entity.setTitle(title);
                    entity.setThumb_media_id(thumb_media_id);
                    entity.setShow_cover_pic(show_cover_pic);
                    entity.setAuthor(author);
                    entity.setDigest(digest);
                    entity.setContent(content);
                    entity.setContent_source_url(content_source_url);
                    try {
                        /**旧的image 没有url 需处理异常 新添加的有url*/
                        String url = json.getString("url");
                        entity.setUrl(url);
                    } catch (Exception e) {
                        System.out.println("url 不存在异常");
                    }
                    lists.add(entity);
                }
            } catch (JSONException e) {  
                accessToken = null;  
                // 获取Material失败  
                System.out.println("jsonObject.getInt(errcode)"+jsonObject.getInt("errcode"));
                System.out.println("jsonObject.getString(errmsg)"+jsonObject.getString("errmsg"));
                log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }  
        return lists;  
    }

这里面需要注意的是  参数对象和 json 字符串 的互转。

 

2、获取图文素材列表

直接上代码

public final static String MATERIAL_LIST = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

/**
* 获取图文(news)素材列表并存入集合中 * @param accessToken 获取接口凭证的唯一标识 * @param type 素材的类型 图文(news) * @param offset 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回 * @param count 返回素材的数量,取值在1到20之间 * @return */

public static List<Material> getMaterialNewsList(String accessToken,String type,int offset,int count) { long totalCount = 0;
String TOTAL_COUNT
= null ; List<Material> lists = new ArrayList<Material>();//定义图文素材实体类集合 String outputStr="";//定义一个空的参数字符串 String requestUrl = MATERIAL_LIST.replace("ACCESS_TOKEN", accessToken);//替换调access_token MaterialParam para = new MaterialParam();//调用接口所需要的参数实体类 para.setType(type); para.setOffset(offset); para.setCount(count); JSONObject jsonObject = new JSONObject(); jsonObject = JSONObject.fromObject(para); outputStr = jsonObject.toString();//将参数对象转换成json字符串 jsonObject = httpsRequest(requestUrl, "POST", outputStr); //发送https请求(请求的路径,方式,所携带的参数) // 如果请求成功 if (null != jsonObject) { try { TOTAL_COUNT = jsonObject.getString("total_count"); JSONArray jsonArray = jsonObject.getJSONArray("item"); for (int i = 0; i < jsonArray.size(); i++) { JSONObject json = (JSONObject) jsonArray.get(i); String MEDIA_ID = json.getString("media_id"); System.out.println("MEDIA_ID "+MEDIA_ID); json = json.getJSONObject("content"); System.out.println(json); JSONArray arr = json.getJSONArray("news_item"); json = (JSONObject) arr.get(0); Material entity = new Material(); String title = json.getString("title"); String author = json.getString("author"); String digest = json.getString("digest"); String thumb_media_id = json.getString("thumb_media_id"); //System.out.println(thumb_media_id); String url = json.getString("url"); String content = json.getString("content"); entity.setTitle(title); entity.setAuthor(author); entity.setDigest(digest); entity.setThumb_media_id(thumb_media_id); entity.setUrl(url); entity.setContent(content); entity.setShow_cover_pic(1); lists.add(entity); } } catch (JSONException e) { accessToken = null; // 获取Material失败 log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } if(!StringUtils.isEmpty(TOTAL_COUNT)){ totalCount = Long.valueOf(TOTAL_COUNT); } return lists; }

 

3、获取其他类型素材

public final static String MATERIAL_LIST = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

/**
     * 获取图片(image)、视频(video)、语音 (voice)素材列表并存入集合中
     * @param accessToken 获取接口凭证的唯一标识
     * @param type 素材的类型,图片(image)、视频(video)、语音 (voice)
     * @param offset 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
     * @param count 返回素材的数量,取值在1到20之间
     * @return
     */
    public static List<MaterialImage> getMaterialImageList(String accessToken,String type,int offset,int count) {
        long totalCount = 0;
        String TOTAL_COUNT = null ;
        List<MaterialImage> lists = new ArrayList<MaterialImage>();//定义图文素材实体类集合
        String outputStr="";//定义一个空的参数字符串
        String requestUrl = MATERIAL_LIST.replace("ACCESS_TOKEN", accessToken);//替换调access_token
        MaterialParam para = new MaterialParam();//调用接口所需要的参数实体类
        para.setType(type);
        para.setOffset(offset);
        para.setCount(count);
        JSONObject jsonObject = new JSONObject();
        jsonObject = JSONObject.fromObject(para);
        outputStr = jsonObject.toString();//将参数对象转换成json字符串

        jsonObject = httpsRequest(requestUrl, "POST", outputStr);  //发送https请求(请求的路径,方式,所携带的参数)
        // 如果请求成功  
        if (null != jsonObject) {
            try {  
                TOTAL_COUNT = jsonObject.getString("total_count");
                JSONArray jsonArray = jsonObject.getJSONArray("item");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = (JSONObject) jsonArray.get(i);
                    System.out.println(json);
                    MaterialImage image = new MaterialImage();
                    String mediaId = json.getString("media_id");
                    String name = json.getString("name");
                    String updateTime = json.getString("update_time");
                    image.setUpdateTime(updateTime);
                    image.setMedia_id(mediaId);
                    image.setName(name);
                    try {
                        /**旧的image 没有url 需处理异常 新添加的有url*/
                        String url = json.getString("url");
                        image.setUrl(url);
                    } catch (Exception e) {
                        System.out.println("url 不存在异常");
                    }
                    lists.add(image);
                }
            } catch (JSONException e) {  
                accessToken = null;  
                // 获取Material失败  
                System.out.println("jsonObject.getInt(errcode)"+jsonObject.getInt("errcode"));
                System.out.println("jsonObject.getString(errmsg)"+jsonObject.getString("errmsg"));
                log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }  
       if(!StringUtils.isEmpty(TOTAL_COUNT)){
            totalCount = Long.valueOf(TOTAL_COUNT);
        }
        
        return lists;  
    }

其中的实体类

/*获取素材列表调用接口所需要的参数实体类**/
public class MaterialParam {
    
    private String type;//素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
    
    private int offset;//从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
    
    private int count;//返回素材的数量,取值在1到20之间

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
    
}
/**素材图片实体类*/
public class MaterialImage {
    
    //要获取的素材的media_id
    private String media_id;
    //文件名称
    private String name;
    //图片的URL
    private String url;
    
    private String updateTime;

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }

    public String getMedia_id() {
        return media_id;
    }

    public void setMedia_id(String media_id) {
        this.media_id = media_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
    
    
}

我也是在学习中,写的有点乱。

其实通过这两节的学习,在开发文档中的接口基本能调用。

今天关于微信大众平台接口微信大众平台接口是什么的介绍到此结束,谢谢您的阅读,有关.net 后台以post方式调用微信公众平台接口、C#-微信公众平台接口-上传临时素材、C#版微信公众平台接口调用源码打包下载、java 调用微信公众平台接口(二)等更多相关知识的信息可以在本站进行查询。

本文标签: