<body> <div> <input type="button" value="头像" οnclick="chooseImage()"/> <div > <input type="button" value="重选" οnclick="chooseImage()"/> <input type="button" value="上传" οnclick="Upload()"/> </div> </div> </body> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script type="text/javascript"> $(function () { var url = location.href.split('#')[0]; var date = "url=" + url; //get中url指后台处理的url,生成签名返回给前端 $.get(url",date, function (data) { var da = $.parseJSON(data); wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: da.appid, // 必填,公众号的唯一标识 timestamp: da.timeStamp, // 必填,生成签名的时间戳 nonceStr: da.nonceStr, // 必填,生成签名的随机串 signature: da.signature,// 必填,签名,见附录1 jsApiList: ["chooseImage", "uploadImage", "downloadImage"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function () { //alert("wx.config success."); // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 }); wx.error(function (res) { alert("wx.config failed."); // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看, // 也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 }); }) }) var images; function chooseImage() { wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 } }); } function uploadImage(localId) { wx.uploadImage({ localId: localId, // 需要上传的图片的本地ID,由chooseImage接口获得 isShowProgressTips: 1, // 默认为1,显示进度提示 success: function (res) { var serverId = res.serverId; // 返回图片的服务器端ID var data="serverId="+serverId; //get中url指后台处理的url,生成签名返回给前端 $.get("url",data,function(r){ if(r>0){ alert("成功"); }else alert("系统异常!,联系管理员"); }) } }); } function Upload(){ uploadImage(images); } </script>
//后端接收方法,生成签名的后台 [HttpGet] public ActionResult XXXX(string url) { string timeStamp = getTimestamp();//时间 string nonceStr = getNoncestr();//随机数 string signature = Weixinjsapi_ticket(timeStamp, nonceStr, url); string appid = appid; String json = "{"; json += "\"timeStamp\":" + "\"" + timeStamp + "\","; json += "\"nonceStr\":" + "\"" + nonceStr + "\","; json += "\"signature\":" + "\"" + signature + "\","; json += "\"appid\":" + "\"" + appid + "\""; json += "}"; return Content(json); } //后端接收方法,下载图片 [HttpGet] public ActionResult XXXX(string mediaId) { try{ if(mediaId!=null&&mediaId!=""){ xxxxx(图片的名称,mediaId); return Content("1"); } } catch(){} return Content("0"); } /// <summary> /// 随机串 /// </summary> public static string getNoncestr() { Random random = new Random(); return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK").ToLower().Replace("s", "S"); } /// <summary> /// 时间截,自1970年以来的秒数 /// </summary> public static string getTimestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// <summary> /// 保存凭证 /// </summary> public static string Asscess { set; get; } /// <summary> /// jsp_api 签名参数 /// </summary> public static string jsapi_ticket{set;get;} /// <summary> /// 保存凭证时间 /// </summary> public static DateTime Asscess_Time { set; get; } /// <summary> /// 保存jsp_api时间 /// </summary> public static DateTime Jsp_Api_Time { set; get; } /// <summary> /// 获取signature /// </summary> /// <returns></returns> public string Weixinjsapi_ticket(string timeStamp, string nonceStr,string url) { if (Asscess == null) { string token = GetToken(appid, secret); Asscess = token; Asscess_Time = DateTime.Now; } else { DateTime time = DateTime.Now; if ((time - Asscess_Time).TotalSeconds > 7000) { string token =GetToken(appid, secret); Asscess = token; Asscess_Time = DateTime.Now; } } if (jsapi_ticket == null) { jsapi_ticket = getjsapi_ticket(Asscess); Jsp_Api_Time = DateTime.Now; } else { DateTime time = DateTime.Now; if ((time - Jsp_Api_Time).TotalSeconds > 7000) { jsapi_ticket = getjsapi_ticket(Asscess); Jsp_Api_Time = DateTime.Now; } } string string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "×tamp=" + timeStamp + "&url="+url; string signature = sha1(string1); return signature; } #region 获取Token /// <summary> /// 获取Token /// </summary> public static string GetToken(string appid, string secret) { var strJson = HttpRequestutil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret),"get"); JavaScriptSerializer json = new JavaScriptSerializer(); token tk = json.Deserialize<token>(strJson); return tk.access_token; } /// <summary> /// 获取jsapi_ticket /// </summary> /// <returns></returns> public static string getjsapi_ticket(string Asscess) { var strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", Asscess), "get"); JavaScriptSerializer json = new JavaScriptSerializer(); token tk = json.Deserialize<token>(strJson); return tk.ticket; } /// <summary> /// 请求Url,不发送数据 /// Method 发送类型(post,get) /// </summary> public static string RequestUrl(string url, string method) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } [Serializable] public class token { /// <summary> /// 凭证 /// </summary> public string access_token { set; get; } /// <summary> /// 有效时间 /// </summary> public string expires_in { set; get; } /// <summary> /// jsp_api签到凭证 /// </summary> public string ticket { set; get; } } /// <summary> /// SHA1加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string sha1(string str) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "sha1"); } /// <summary> /// 下载微信头像图片 /// </summary> private void xxxxx(string PatnName,string media) { if (Asscess == null) { string token = GetToken(appid, secret); Asscess = token; Asscess_Time = DateTime.Now; } else { DateTime time = DateTime.Now; if ((time - Asscess_Time).TotalSeconds > 7000) { string token =GetToken(appid, secret); Asscess = token; Asscess_Time = DateTime.Now; } } string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", Asscess , media) WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream reader = response.GetResponseStream(); FileStream writer = new FileStream(GetPath(PatnName), FileMode.OpenOrCreate, FileAccess.Write); byte[] buff = new byte[512]; int c = 0; //实际读取的字节数 while ((c = reader.Read(buff, 0, buff.Length)) > 0) { writer.Write(buff, 0, c); } writer.Close(); writer.Dispose(); reader.Close(); reader.Dispose(); response.Close(); } /// <summary> /// 保存图片地址 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GetPath(string fileName) { string path = "";//写上地址 path = Server.MapPath(path); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += fileName + ".jpg"; return path; } public const string appid = "";//公众号ID public const string secret = "";//微信公众号的secret 相关代码地址:https://gitee.com/qq-w/wechat.git
转载于:https://blog.51cto.com/13336347/1970234