C# 微信开发-----微信会员卡(三)激活会员卡

在会员领取了会员卡之后需要做 一个跳转性激活,模式请看下图:

在创建会员卡的时候需要配置下这个参数的值:

 memberActivate.aspx页面代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="memberActivate.aspx.cs" Inherits="ChainStock.mobile.member.memberActivate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>激活会员卡</title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <%--<script src="scripts/bootstrap.min.js" type="text/javascript"></script>--%>
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <style type="text/css">
        .no-padding {
            padding: 0px;
        }

        .no-margin {
            margin: 0px;
        }

        .btn_active {
            background-color: #019a01;
            width: 100%;
            padding: 7px 0px;
            color: white;
            border: 1px solid #019a01;
        }

        .btn_return {
            background-color: #f8f8f8;
            width: 100%;
            padding: 7px 0px;
            color: black;
            border: 1px solid #e6e6e6;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $(".btn_return").bind("click", function () {
                event.preventDefault();
                window.history.back();
            })
        });
    </script>
</head>
<body style="background-color: #f2f2f2;" class="no-padding no-margin">
    <form id="form1" runat="server">
        <div class="container no-padding">
            <br />
            <div class="col-xs-12">
                <div class="col-xs-12">
                    <label>请确定以下信息:</label>

                </div>
            </div>
            <div class="clearfix"></div>
            <br />
            <div style="background-color: white; padding: 30px 0px; border-bottom: 1px solid #dbdbdb; border-top: 1px solid #dbdbdb;">
                <div class="col-xs-12">
                    <div class="col-xs-3">
                        用户名
                    </div>
                    <div class="col-xs-9 no-padding text-left" id="divMemName" runat="server"></div>
                    <div class="clearfix"></div>
                </div>
                <div class="col-xs-12" style="padding-top: 10px;">
                    <div class="col-xs-3">
                        手机号
                    </div>
                    <div class="col-xs-9 no-padding text-left" id="divMemMobile" runat="server">
                    </div>
                    <div class="clearfix"></div>
                </div>
                <div class="clearfix"></div>
            </div>
            <br />

            <div class="col-xs-12 no-padding">
                <div class="col-xs-12 text-center">
                    <input type="button" class="btn btn-sm btn_active" value="激活会员卡" id="btnActiveMem" />
                    <input type="hidden" id="hd_MemMobile" value="" runat="server" />
                    <input type="hidden" id="hd_CardCode" value="" runat="server" />
                    <input type="hidden" id="hd_CardId" value="" runat="server" />
                </div>

                <div class="col-xs-12 text-center">
                    <br />
                    <input type="button" class="btn btn-sm btn_return" value="返 回" />
                </div>
                <div class="col-xs-12 ">
                    <h6 style="color: red;">注:激活后不可修改上面的信息</h6>
                </div>

                <div class="clearfix"></div>
            </div>
        </div>
    </form>

    <script type="text/javascript" src="scripts/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <script type="text/javascript">
        $(function () {
            //激活会员卡
            $("#btnActiveMem").click(function () {
                $.ajax({
                    type: "GET",
                    url: "../../Service/AjaxService.ashx?Method=Wx_ActivateCard",
                    data: {
                        memMobile: $("#hd_MemMobile").val(),
                        cardCode: $("#hd_CardCode").val(),
                        cardId: $("#hd_CardId").val()
                    },
                    dataType: "text",
                    success: function (result) {
                        if (result != null && result != "") {
                            switch (result) {
                                case "0":
                                    alert("系统错误,请稍后再试");
                                    break;
                                case "-1":
                                    alert("系统异常,请联系管理员");
                                    break;
                                case "-2":
                                    alert("您还不是会员,激活失败");
                                    break;
                                default:
                                    alert("激活成功");
                                    wx.closeWindow();//这一步就是会员激活了之后就自动跳转到会员卡详细页面
                            }
                        }
                    }
                });
            });
        })
    </script>
</body>
</html>

后台代码:

using Chain.Wechat;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ChainStock.mobile.member
{
    public partial class memberActivate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            BindData();

        }
        void BindData()
        {
            string code = "";
            string openid = "";
            string access_token = "";
            string strEncrypt_code = "";
            string tick_code = "";
            string strActivate_ticket = "";
            string cardId = "";

            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["encrypt_code"]))
                {
                    strEncrypt_code = Request.QueryString["encrypt_code"].ToString();
                }
                if (!string.IsNullOrEmpty(Request.QueryString["card_id"]))
                {
                    cardId = Request.QueryString["card_id"].ToString();
                    hd_CardId.Value = cardId;
                }
                string getAuthorize = GetAuthorize();
                if (getAuthorize != "")
                {
                    getAuthorize = "[" + getAuthorize + "]";

                    Newtonsoft.Json.Linq.JArray javascript = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(getAuthorize);
                    Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)javascript[0];

                    if (obj["access_token"] != null && obj["access_token"].ToString() != "")
                    {
                        access_token = obj["access_token"].ToString();//用户OpenID             
                    }
                }
                if (!string.IsNullOrEmpty(access_token))
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["encrypt_code"]))
                    {
                        strEncrypt_code = Request.QueryString["encrypt_code"].ToString();
                        string postUrl = "https://api.weixin.qq.com/card/code/decrypt?access_token=" + access_token;
                        string postDate = "{\"encrypt_code\":\"" + strEncrypt_code + "\"}";

                        string strResult = PostWebRequest(postUrl, postDate);
                        strResult = "[" + strResult + "]";
                        Newtonsoft.Json.Linq.JArray codeArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strResult);
                        Newtonsoft.Json.Linq.JObject objResult = (Newtonsoft.Json.Linq.JObject)codeArray[0];
                        if (objResult["errmsg"].ToString() == "ok")
                        {
                            code = objResult["code"].ToString();
                            hd_CardCode.Value = code;
                            if (!string.IsNullOrEmpty(Request["activate_ticket"]))
                            {
                                strActivate_ticket = Request["activate_ticket"].ToString();
                            }

                            if (!string.IsNullOrEmpty(strActivate_ticket))
                            {
                                string ticketPostUrl = "https://api.weixin.qq.com/card/membercard/activatetempinfo/get?access_token=" + access_token;
                                string ticketPostData = "{ \"activate_ticket\" : \"" + strActivate_ticket + "\"}";
                                string userInfoResult = PostWebRequest(ticketPostUrl, ticketPostData);
                                userInfoResult = "[" + userInfoResult + "]";

                                Newtonsoft.Json.Linq.JArray userInfoArray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(userInfoResult);
                                Newtonsoft.Json.Linq.JObject objUserInfo = (Newtonsoft.Json.Linq.JObject)userInfoArray[0];
                                if (objUserInfo["errmsg"].ToString() == "ok")
                                {
                                    string userMobile = objUserInfo["info"]["common_field_list"][0]["value"].ToString();
                                    string userName = objUserInfo["info"]["common_field_list"][1]["value"].ToString();
                                    if (!string.IsNullOrEmpty(userMobile))
                                    {
                                        hd_MemMobile.Value = userMobile;
                                        divMemMobile.InnerText = userMobile;
                                        divMemName.InnerText = userName;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PubFunction.LogError("微信激活会员授权异常:" + ex);
            }
        }


        //通过code换取网页授权access_token
        public string GetAuthorize()
        {
            //PubFunction.curParameter.strWeiXinAppID = "wxcb014df3a2583811";
            //PubFunction.curParameter.strWeiXinAppSecret = "1fb18946950b112cd79103a7b1f9249b";
            if (PubFunction.curParameter.strWeiXinAppID != null && PubFunction.curParameter.strWeiXinAppSecret != null)
            {
                string templateUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
                templateUrl = string.Format(templateUrl, PubFunction.curParameter.strWeiXinAppID, PubFunction.curParameter.strWeiXinAppSecret);
                HttpRequestHelper hrh = new HttpRequestHelper();
                return hrh.Reqeust(templateUrl);
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 发送Post请求到微信端
        /// </summary>
        /// <param name="postUrl">请求的路径</param>
        /// <param name="paramData">发送的数据</param>
        /// <returns></returns>
        public string PostWebRequest(string postUrl, string paramData)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                PubFunction.LogError(ex);
            }
            return ret;

        }
    }
}

激活时我使用了一般处理程序来激活的代码如下:这个是根据我的系统做了一个判断,是我系统中的会员才能激活,否则不能激活

#region 跳转式激活会员卡 参考:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283   6.6.2
        public void Wx_ActivateCard()
        {
            int flag = 0;
            string access_token = "";
            try
            {
                string strMemMobile = !string.IsNullOrEmpty(Request["memMobile"]) ? Request["memMobile"].ToString() : "";//手机号
                string strCardCode = !string.IsNullOrEmpty(Request["cardCode"]) ? Request["cardCode"].ToString() : "";//卡Code
                string strCardId = !string.IsNullOrEmpty(Request["cardId"]) ? Request["cardId"].ToString() : "";//卡ID
                if (!string.IsNullOrEmpty(strMemMobile))
                {
                    Chain.BLL.Mem bllMem = new Chain.BLL.Mem();
                    DataTable dtMem = bllMem.GetList(" MemMobile='" + strMemMobile + "' ").Tables[0];
                    if (dtMem.Rows.Count > 0)//执行激活(只有系统中的会员才能激活)
                    {
                        string getAuthorize = GetAuthorize();
                        if (getAuthorize != "")
                        {
                            getAuthorize = "[" + getAuthorize + "]";

                            Newtonsoft.Json.Linq.JArray javascript = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(getAuthorize);
                            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)javascript[0];

                            if (obj["access_token"] != null && obj["access_token"].ToString() != "")
                            {
                                access_token = obj["access_token"].ToString();
                            }
                            if (!string.IsNullOrEmpty(strCardCode) && !string.IsNullOrEmpty(strCardId))
                            {
                                string postData = "{";
                                postData += "\"membership_number\": \"" + strMemMobile + "\",";
                                postData += "\"code\": \"" + strCardCode + "\",";
                                postData += "\"card_id\": \"" + strCardId + "\"";
                                postData += "}";
                                string postUrl = "https://api.weixin.qq.com/card/membercard/activate?access_token=" + access_token;
                                string result = PostWebRequest(postUrl, postData);

                                if (!string.IsNullOrEmpty(result))
                                {
                                    result = "[" + result + "]";
                                    Newtonsoft.Json.Linq.JArray cardResult = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(result);
                                    Newtonsoft.Json.Linq.JObject cardObj = (Newtonsoft.Json.Linq.JObject)cardResult[0];

                                    if (cardObj["errmsg"] != null && cardObj["errmsg"].ToString() != "")
                                    {
                                        if (cardObj["errmsg"].ToString() == "ok")
                                        {
                                            flag = 1;
                                        }
                                        else
                                        {
                                            flag = -1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else//禁止激活 
                    {
                        flag = -2;
                    }
                }
                else
                {
                    flag = -1;
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
                flag = -1;
            }
            Context.Response.Write(flag);
        }
        #endregion

猜你喜欢

转载自www.cnblogs.com/LoveQin/p/10176045.html