Asp.net MVC微信开发——微信分享接口

当你的网站链接在微信内打开时,我们有时候会将这个链接分享给朋友或者分享到朋友圈

如果接入了微信分享的接口,就会如下图B的形式呈现,如果没有接入,则会以A的形式呈现

Asp.net MVC微信开发——微信分享接口_第1张图片

我们当然会希望以B的形式呈现,不仅好看而且显得专业。这篇内容为大家分享一下我怎样接入微信分享的接口。

第一步,准备工作

你需要注册好一个公众号且认证通过,得到属于自己的AppID和AppSecret配置好JS接口的安全域名

第二步,在你想要分享的页面的控制程序中配置Wx.config的信息

上代码,代码中有很详细的注释

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;

namespace XunYouWeb.Controllers
{
	//wx.config数据实体类
    public class WXShareModel
    {
        public string appId { get; set; }
        public string nonceStr { get; set; }
        public string timestamp { get; set; }

        public string signature { get; set; }

        public string ticket { get; set; }
        public string url { get; set; }

        public void MakeSign()
        {
            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(ticket).Append("&")
                         .Append("noncestr=").Append(nonceStr).Append("&")
                         .Append("timestamp=").Append(timestamp).Append("&")
                         .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            var string1 = string1Builder.ToString();
            signature = Sha1(string1, Encoding.Default);//GetSwcSH1(string1);

        }

        public static string Sha1(string orgStr, Encoding encode)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_in = encode.GetBytes(orgStr);
            byte[] bytes_out = sha1.ComputeHash(bytes_in);
            sha1.Dispose();
            string result = BitConverter.ToString(bytes_out);
            result = result.Replace("-", "");
            return result;
        }

    }

    //Jsapiticket实体类
    public class Jsapiticket
    {
        public string ticket { get; set; }
        public DateTime expires_in { get; set; }
    }

    public class WechatController : BaseController
    {
        public static readonly string appid =System.Web.Configuration.WebConfigurationManager.AppSettings["AppId"];
        public static string _ticket = "";
        public static DateTime lastTimestamp;

        //我的内容页,也是我想要分享出去的页面
        public ActionResult wcpcdetail()
        {
            string ticket ="";

            Jsapiticket ticketModel = new Jsapiticket();
            if (System.Web.HttpContext.Current.Application["jsapiTicket"] != null)
            {
                ticketModel = System.Web.HttpContext.Current.Application["jsapiTicket"] as Jsapiticket; //取缓存的ticket
            }
            else
            {
                System.Web.HttpContext.Current.Application["jsapiTicket"] = ticketModel; //存一个空的ticket
            }

            if (string.IsNullOrEmpty(ticketModel.ticket) || lastTimestamp == null || (lastTimestamp - DateTime.Now).Milliseconds >= 7200) //验证是否过期
            {
                ticket = Helper.Comm.HttpPost2(ip + "/api/Index/CreateTicket", null);  //获取API接口中生成的ticket
                ticket = ticket.Trim('"');
                lastTimestamp = DateTime.Now;
                if (string.IsNullOrEmpty(ticket))
                {
                    return Json(new { issuccess = false, error = "获取ticket失败" });
                }
                SaveTicket(ticket);
            }
            else
            {
                ticket = ticketModel.ticket;
            }

            var model = new WXShareModel();
            model.appId = appid;
            model.nonceStr = CreateNonceStr();
            model.timestamp = GetTimeStamp();
            model.ticket = ticket;
            model.url = Request.Url.AbsoluteUri.Split('#')[0];
            model.MakeSign();
            return View(model);  //把数据model返回到页面

        }


        //缓存获取到的jsapiticket   (access_token和jsapiticket都是有7200秒的过期时间, 并且每天生成的次数有限制,所以必须缓存) 
        //这里我只缓存ticket,如果ticket过期了,access_token也重新生成
        public static void SaveTicket(string ticket)
        {
            var jsapiTicket = new Jsapiticket();
            jsapiTicket.ticket = ticket;
            jsapiTicket.expires_in = DateTime.Now;
            //存储
            System.Web.HttpContext.Current.Application["jsapiTicket"] = jsapiTicket;
        }

        //生成nonceStr,微信需要这个字段来保证生成signature的唯一性
        private string CreateNonceStr(int length = 16)
        {
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            for (int i = 0; i < length; i++)
            {
                Random v = new Random(Guid.NewGuid().GetHashCode()); //加入随机数种子,保证循环出的是不一样的值
                int index = v.Next(chars.Length);
                str += chars.Substring(index, 1);
            }
            return str;
        }

        //返回需要的时间戳
        private static string GetTimeStamp() 
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

    }
}

 

第三步,在API中生成access_token和jsapiticket

ps:我的项目考虑到多平台的使用,所以用到了API接口,也可以不用,方法基本是一致的,只需要把appid和secret换成你自己的就好

上代码

using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Helper;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Net.Http;
using System.IO;

namespace WebApi.Controllers
{
    #region 自定义实体类
    public class WechatModels
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
    }

    public class TicketModel
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public int expires_in { get; set; }
    }
    #endregion

    public class IndexController : ApiController
    {
        /// 
        /// 获取ticket
        /// 
        /// 
        [HttpPost]
        public IHttpActionResult CreateTicket(dynamic data)
        {
            //get accesstoken 
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=******&secret=******");
            var wm = new System.Net.Http.HttpClient().GetAsync(url).Result.Content.ReadAsStringAsync().Result;
            WechatModels info = JsonConvert.DeserializeObject(wm);

            //get ticket  
            string turl = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", info.access_token);
            var tickets = new System.Net.Http.HttpClient().GetAsync(turl).Result.Content.ReadAsStringAsync().Result;
            TicketModel tinfo = JsonConvert.DeserializeObject(tickets);
            return Json(tinfo.ticket.Trim('"'));
        }
    }
}


最后一步,前台视图页面

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    

title

content

至此就完成了所有的工作!测试成功!

Asp.net MVC微信开发——微信分享接口_第2张图片

 

需要注意的点:

1.分享测试都需要放在服务器上才能成功,也可以使用微信官方提供的微信开发者工具

2.一开始测试的时候开启debug模式,每次打开页面都会弹出消息,通过弹出消息判断问题

3.微信公众平台的运维中心中有一个日志查询,可以查询自己的接口被调用的情况,配合查找问题

4.微信提供了接口签名校验工具 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign

5.开发的时候肯定无数次看到“nvalid signature”这个报错,冷静下来,一步步的排查才能最终解决

 

希望这篇案例对大家有帮助!

你可能感兴趣的:(微信开发)