C# 微信開發-----微信會員卡(三)啟用會員卡
阿新 • • 發佈:2018-12-25
在會員領取了會員卡之後需要做 一個跳轉性啟用,模式請看下圖:
在建立會員卡的時候需要配置下這個引數的值:
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