您的位置:首页 > 移动开发 > 微信开发

微信分享自定义链接、自定义参数(全栈)

2019-02-27 11:01 225 查看

HTML

    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <script src="js/jquery.min.js"></script>
    <script src="layer/layer.js"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>  <!--引入微信js-->
    <script src="js/jquery.cookie.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>

<style>

/*******************
   770055749@qq.com
    2019-02-27  No.1
*******************/

* {
    margin:0px;
    padding:0px;
    font-family:"微软雅黑";
    text-decoration:none;
    list-style:none;
}

.share {
    width:100%;
    height:15vw;
    background:rgb(2,216,252);
    position:fixed;
    bottom:0vw;
    left:0vw;
}
.share span{
    display:block;
    width:100%;
    text-align:center;
    line-height:15vw;
    color:#fff;
    cursor:pointer;
    font-size:1rem;
}

.posMask {
    width:100%;
    /*height:367px;*/
    background:rgba(0,0,0,.5);
    z-index:10;
    position:fixed;
    left:0vw;
    top:0vw;
}
.posMask  .sharePic{
    position:absolute;
    right: 15px;
    z-index:11;
    top:10px;
}
.posMask  .sharePic img {
    width: 260px;
    height: 180px;
}

</style>

<!--分享按钮-->

<div class="share"><span>我要分享</span></div>

<!--分享遮罩-->

 <div class="posMask">
       <div class="sharePic">
               <img src="images/guide1.png" />
      </div>    
</div>

JavaScript

/// <reference path="jquery.min.js" />

var obj = {
    init: function () {
        $.ajax({
            url: "获取当前那个用户分享的id",
            data: {
                "itype": "search",
                "lxdh": localStorage.Phone,
            },
            success: function (res) {
                var demo = jQuery.parseJSON(res);
                obj.bind(demo.id,demo.title,demo.dspt);
            }

        });
    },
    bind: function (userId,title,dspt) {
        console.log(userId);
        //点击遮罩
        $(".posMask").on('click', function () {
            $(this).css("height", "0px")
        })
        $(".shareWelcome").on('click', function () {
            var _timestamp;
            var _nonceStr;
            var _signature;
            var _ticket;


            var url = window.location.href.split('#')[0];  
            url = url.replace(/&/g, '%26');  //将地址栏中带有&后缀的替换成%26 因为点击分享自动追加后缀名,如果存在多个参数注释改代码,无妨!!!!

        //朋友圈 from=timeline&isappinstalled=0 
       //微信群 from=groupmessage&isappinstalled=0 
       //好友分享 from=singlemessage&isappinstalled=0

            $.ajax({
                type: "get",
                url: "ashx/WelcomeManager.ashx", //将当前url传入后端进行微信签名
                dataType: "text",
                ifModified: true,
                cache: false,
                data: { "itype": "WeClomeContent", "absoluteuri": url },
                timeout: 10000,
                async: false,
                beforeSend: function (XMLHttpRequest) {
                },
                success: function (msg) {
                    $(".posMask").css("height", $("body,html").height() + "px")
                    _timestamp = msg.split("@")[0];
                    _nonceStr = msg.split("@")[1];
                    _signature = msg.split("@")[2];
                    _ticket = msg.split("@")[3];
                    console.log(_timestamp, _nonceStr, _signature, _ticket);
                    wx.config({
                        debug: true,    // true 调试模式 false取消
                        appId: 'appid', // 必填,公众号的唯一标识
                        timestamp: _timestamp,     // 必填,生成签名的时间戳
                        nonceStr: _nonceStr,        // 必填,生成签名的随机串
                        signature: _signature,      // 必填,签名,见附录1
                        jsApiList: [
                                'checkJsApi',
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                "onMenuShareQQ",
                                "onMenuShareWeibo"
                        ]
                    });
                },
                error: function (data) {
                    layer.msg("分享失败!");
                }
            });

            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                var shareData = {
                    title:title,
                    desc: dspt,//这里请特别注意是要去除html 
                    link: url,
                    imgUrl: 'http://www.******.com/wap/img/icon.jpg',  //分享图片
                    success: function () {
                        layer.msg('已分享');
                        $(".posMask").css("height", $("body,html").height() + "px");
                    },
                    cancel: function () {
                        layer.msg('取消分享');
                    },
                };
                wx.onMenuShareAppMessage(shareData);
                wx.onMenuShareTimeline(shareData);
                wx.onMenuShareQQ(shareData);
                wx.onMenuShareWeibo(shareData);

                //随意地址动态配置分享
                shareData.title = '********';
                shareData.link = 'http://www.******.com/wap/login.html?type=user&userId=' + userId;
            });

        })
    }
};
$(function () {
    obj.init();
    //保存当前页面cook
    $.cookie("name", "value");
})

C#

<%@ WebHandler Language="C#" Class="WelcomeManager" %>

using System;
using System.Collections;
using System.Text;
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.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Web.SessionState;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.IO;

public class WelcomeManager : IHttpHandler
{
    JavaScriptSerializer jss = new JavaScriptSerializer();
    HttpContext context = null;
    string sResult = "";
    public string ticket = string.Empty;
    public string timestamp = "";
    public string nonceStr = "";
    public string signature = "";

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        this.context = context;
        string type = context.Request.Params["itype"].ToString();
        switch (type)
        {
            case "WeClomeContent":
                WeClomeContent();
                break;
        }
    }
    /// <summary>
    /// 微信分享
    /// </summary>
    protected void WeClomeContent()
    {
        StringBuilder strBul = new StringBuilder();
        string res = "";
        string absoluteuri = context.Request.Params["absoluteuri"].ToString();
        ticket = Senparc.Weixin.MP.Containers.JsApiTicketContainer.TryGetJsApiTicket(PublicParam._AppId, PublicParam._AppSecret);
        timestamp = Senparc.Weixin.MP.Helpers.JSSDKHelper.GetTimestamp();
        nonceStr = Senparc.Weixin.MP.Helpers.JSSDKHelper.GetNoncestr();
        signature = Senparc.Weixin.MP.Helpers.JSSDKHelper.GetSignature(ticket, nonceStr, timestamp, absoluteuri);
        res = timestamp + "@" + nonceStr + "@" + signature + "@" + ticket + "@";
        strBul.Append(res);
        context.Response.Write(strBul);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

SQL SERVER

create table shareDemo
(
id int primary key IDentity(1,1),
oldUserId int,
newUserId int,
[dateTime] datetime,
)

//当分享成功是用户点击进来是 该链接url为:http://www.******.com/wap/login.html?type=user&userId=' + userId

(1)保存当前分享用户id

(2)当邀请用户注册时,在shareDemo table中添加数据

(3)新用户注册成功,按照项目需求进行业务逻辑处理数据

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: