項目需求:分享一篇微信文章,文章中嵌入圖片和文字等。在文章的底部有一個二維碼,用於掃描進入另外一個頁面去採集用戶的報名數據。javascript
實現步驟以下:css
階段一:微信公衆號html
一、申請一個微信公衆號,因爲考慮到是小範圍使用,申請的是我的號。公衆號申請步驟參考文章:http://jingyan.baidu.com/article/6525d4b134051eac7d2e9417.htmljava
二、在‘素材管理’中,導入圖片等信息。"圖文消息"中去編輯微信文章。編輯完畢後保存jquery
三、在「自定義菜單」項中去定義菜單,並將某個菜單指向爲以前保存的「圖文消息」web
階段二:信息採集功能開發sql
一、搭建一個空網站,安裝插件:bootstrap、 jquery、bootstrapValidator。bootstrapValidator用做表單驗證。數據庫
二、新建一個html頁面,佈局標籤等信息。將提交的標籤信息放置在form表單中。在表單標籤中指定提交跳轉的aciton,本項目指向一個通常處理程序:action="Handler.ashx" 完整代碼以下:bootstrap
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>"少年讀書說"線上報名</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"> <link href="Content/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="Content/bootstrapValidator.min.css" rel="stylesheet" media="screen" /> <script src="Scripts/jquery-3.1.1.min.js"></script> <script src="Scripts/bootstrap.min.js"></script> <script src="Scripts/bootstrapValidator.min.js"></script> <script> $(function () { $('#defaultForm').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { username: { message: '用戶名驗證失敗', validators: { notEmpty: { message: '用戶名不能爲空' } } }, sex: { message: '性別驗證失敗', validators: { notEmpty: { message: '性別不能爲空' } } }, age: { message: '年齡驗證失敗', validators: { notEmpty: { message: '年齡不能爲空' }, between: { min: 3, max: 10, message: '年齡範圍3-10歲' } } }, phone: { validators: { notEmpty: { message: '手機號碼不能爲空' }, regexp: { regexp: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/, message: '請輸入正確的電話號碼' } } }, parenter: { message: '家長姓名驗證失敗', validators: { notEmpty: { message: '家長姓名不能爲空' } } } }, submitHandler: function (validator, form, submitButton) { alert("你好"); } }); //$('#saveMsg').click(function () { // $('#defaultForm').bootstrapValidator('validate'); //}); //$("#defaultForm").submit(function (ev) { ev.preventDefault(); }); //$("#saveMsg").on("click", function () { // var bootstrapValidator = $("#defaultForm").data('bootstrapValidator'); // bootstrapValidator.validate(); // if (bootstrapValidator.isValid()) { // $("#defaultForm").submit(); // alert("成功"); // } // else return; //}); }); //function showPopover(target, msg) { // target.attr("data-original-title", msg); // $('[data-toggle="tooltip"]').tooltip(); // target.tooltip('show'); // target.focus(); // //2秒後消失提示框 // var id = setTimeout( // function () { // target.attr("data-original-title", ""); // target.tooltip('hide'); // }, 2000 // ); //} </script> </head> <body> <div class="panel panel-info"> <div class="panel-heading"> <img src="img/mmexport1496838159618.jpg" class="img-responsive center-block" /> </div> <div class="panel-body"> <form id="defaultForm" class="form-horizontal" role="form" action="Handler.ashx" method="post"> <div class="form-group"> <label for="username" class="col-sm-2 control-label"> 小選手姓名: </label> <div class="col-sm-10"> <input type="text" name="username" class="form-control" placeholder="請輸入選手姓名" id="username" /> </div> </div> <div class="form-group"> <label for="sex" class="col-sm-2 control-label"> 小選手性別: </label> <div class="col-sm-10"> <select class="form-control" id="sex" name="sex"> <option value="男">男</option> <option value="女">女</option> </select> </div> </div> <div class="form-group"> <label for="age" class="col-sm-2 control-label"> 小選手年齡: </label> <div class="col-sm-10"> <input type="text" name="age" class="form-control" placeholder="請輸入選手年齡" id="age" /> </div> </div> <div class="form-group"> <label for="parenter" class="col-sm-2 control-label"> 家長姓名: </label> <div class="col-sm-10"> <input type="text" name="parenter" class="form-control" placeholder="請輸入家長姓名" id="parenter" /> </div> </div> <div class="form-group"> <label for="phone" class="col-sm-2 control-label"> 家長手機號: </label> <div class="col-sm-10"> <input type="text" name="phone" class="form-control" placeholder="請輸入手機號碼" id="phone" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button id="saveMsg" name="saveMsg" type="submit" class="btn btn-primary btn-block"> 提交 </button> </div> </div> </form> </div> </div> </body> </html>
三、通常處理程序中完成信息的獲取和提交。須要在該頁中引入對數據庫的操做代碼,信息保存完畢後輸出信息成功的提示。完整代碼:瀏覽器
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Data; using Oracle.ManagedDataAccess.Client; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { //text/plain表示是普通文本,瀏覽器會原封不動的顯示它獲得的內容 //"text/html"表示是超文本內容,瀏覽器會把它獲得的內容按html格式進行處理後顯示 //context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/html"; string username = context.Request.Form["username"].ToString(); string sex = context.Request.Form["sex"].ToString(); int age = Convert.ToInt32(context.Request.Form["age"].ToString()); string parenter = context.Request.Form["parenter"].ToString(); string phone = context.Request.Form["phone"].ToString(); string connStr = string.Format("Data Source={0}:{1}/{2};User Id={3};Password={4};Connection Timeout =3600", "0.0.0.0", "1521","ORCL", "WX", "WX"); string sql = string.Format(@"INSERT INTO READ_BOOK_USER(USERNAME,SEX,AGE,PARENTER,PHONE) VALUES('{0}','{1}',{2},'{3}','{4}')", username, sex, age, parenter, phone); int rs= ExecuteNonQuery(connStr, CommandType.Text, sql); //context.Response.Write("<script type='text/javascript'>alert('123')</script>"); String output = string.Format("<span style='font-size:25px;'>恭喜您!「少年讀書說」報名成功!</span>"); context.Response.Write(output); //context.Response.Write("恭喜您!「少年讀書說」報名成功!"); //context.Response.Redirect("ReadBook.html"); } public bool IsReusable { get { return false; } } #region oracle數據庫操做 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Execute a database query which does not include a select /// </summary> /// <param name="connString">Connection string to database</param> /// <param name="cmdType">Command type either stored procedure or SQL</param> /// <param name="cmdText">Acutall SQL Command</param> /// <param name="commandParameters">Parameters to bind to the command</param> /// <returns></returns> public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { // Create a new Oracle command OracleCommand cmd = new OracleCommand(); //Create a connection using (OracleConnection connection = new OracleConnection(connectionString)) { //Prepare the command PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); //Execute the command int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute an OracleCommand (that returns no resultset) against an existing database transaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="trans">an existing database transaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OracleTransaction trans, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute an OracleCommand (that returns no resultset) against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(OracleConnection connection, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a select query that will return a result set /// </summary> /// <param name="connString">Connection string</param> //// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns></returns> public static OracleDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { //Create the command and connection OracleCommand cmd = new OracleCommand(); OracleConnection conn = new OracleConnection(connectionString); try { //Prepare the command to execute PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); //Execute the query, stating that the connection should close when the resulting datareader has been read OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { //If an error occurs close the connection as the reader will not be used and we expect it to close the connection conn.Close(); throw; } } public static OracleDataReader ExecuteReader(OracleConnection conn, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { //Create the command and connection OracleCommand cmd = new OracleCommand(); try { //Prepare the command to execute PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); //Execute the query, stating that the connection should close when the resulting datareader has been read OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { //If an error occurs close the connection as the reader will not be used and we expect it to close the connection conn.Close(); throw; } } /// <summary> /// Execute an OracleCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); using (OracleConnection conn = new OracleConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } public static IDataReader ExecuteDataReader(string connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); using (OracleConnection conn = new OracleConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); IDataReader val = cmd.ExecuteReader(); cmd.Parameters.Clear(); return val; } } public static IDataReader ExecuteDataReader(OracleConnection conn, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); IDataReader val = cmd.ExecuteReader(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a OracleCommand (that returns a 1x1 resultset) against the specified SqlTransaction /// using the provided parameters. /// </summary> /// <param name="transaction">A valid SqlTransaction</param> /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">The stored procedure name or PL/SQL command</param> /// <param name="commandParameters">An array of OracleParamters used to execute the command</param> /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns> public static object ExecuteScalar(OracleTransaction transaction, CommandType commandType, string commandText, params OracleParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // Create a command and prepare it for execution OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters); // Execute the command & return the results object retval = cmd.ExecuteScalar(); // Detach the SqlParameters from the command object, so they can be used again cmd.Parameters.Clear(); return retval; } /// <summary> /// Execute an OracleCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(conn, CommandType.StoredProcedure, "PublishOrders", new OracleParameter(":prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or PL/SQL command</param> /// <param name="commandParameters">an array of OracleParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(OracleConnection connectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connectionString, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// <summary> /// Add a set of parameters to the cached /// </summary> /// <param name="cacheKey">Key value to look up the parameters</param> /// <param name="commandParameters">Actual parameters to cached</param> public static void CacheParameters(string cacheKey, params OracleParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Fetch parameters from the cache /// </summary> /// <param name="cacheKey">Key to look up the parameters</param> /// <returns></returns> public static OracleParameter[] GetCachedParameters(string cacheKey) { OracleParameter[] cachedParms = (OracleParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; // If the parameters are in the cache OracleParameter[] clonedParms = new OracleParameter[cachedParms.Length]; // return a copy of the parameters for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (OracleParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// Internal function to prepare a command for execution by the database /// </summary> /// <param name="cmd">Existing command object</param> /// <param name="conn">Database connection object</param> /// <param name="trans">Optional transaction object</param> /// <param name="cmdType">Command type, e.g. stored procedure</param> /// <param name="cmdText">Command test</param> /// <param name="commandParameters">Parameters for the command</param> private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, CommandType cmdType, string cmdText, OracleParameter[] commandParameters) { //Open the connection if required if (conn.State != ConnectionState.Open) conn.Open(); //Set up the command cmd.Connection = conn; cmd.CommandText = cmdText; cmd.CommandType = cmdType; //Bind it to the transaction if it exists //if (trans != null) // cmd.Transaction = trans; // Bind the parameters passed in if (commandParameters != null) { foreach (OracleParameter parm in commandParameters) cmd.Parameters.Add(parm); } } /// <summary> /// Converter to use boolean data type with Oracle /// </summary> /// <param name="value">Value to convert</param> /// <returns></returns> public static string OraBit(bool value) { if (value) return "Y"; else return "N"; } /// <summary> /// Converter to use boolean data type with Oracle /// </summary> /// <param name="value">Value to convert</param> /// <returns></returns> public static bool OraBool(string value) { if (value.Equals("Y")) return true; else return false; } public static DataSet ExecuteDataset(string ConnectionString, CommandType cmdType, string cmdText, params OracleParameter[] commandParameters) { //Create the command and connection OracleConnection conn = new OracleConnection(ConnectionString); conn.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandText = cmdText; cmd.CommandType = CommandType.Text; OracleDataAdapter oda; //DataSet ds = new DataSet(); DataSet ds; try { oda = new OracleDataAdapter(cmd); ds = new DataSet(); oda.Fill(ds, "temp"); ////Prepare the command to execute //PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); ////Execute the query, stating that the connection should close when the resulting datareader has been read //OracleDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); //cmd.Parameters.Clear(); conn.Close(); return ds; } catch (Exception err) { //If an error occurs close the connection as the reader will not be used and we expect it to close the connection conn.Close(); throw err; } //return ds; } #endregion }
四、因爲返回的信息有顯示格式要求,故須要將ContentType 的類型修改成 "text/html"
"text/plain"表示是普通文本,瀏覽器會原封不動的顯示它獲得的內容
"text/html"表示是超文本內容,瀏覽器會把它獲得的內容按html格式進行處理後顯示
五、數據庫的連接串能夠寫在web.config配置文件中,而後在此處獲取。
六、須要在通常處理程序中加入對數據庫的操做ado語句,本項目使用的oracle,引入的dll文件名爲Oracle.ManagedDataAccess.dll dll下載
七、將網站發佈,部署到已準備好的服務器上面。
階段三:網站域名的申請
一、因爲在微信端訪問無域名的網站(帶ip)會提示是否繼續訪問的環節,使用體檢差。故須要將服務器ip申請爲域名
二、域名申請方式:買的阿里雲域名。我是先在萬網上購買了一個域名而後實名認證,再域名備案等等操做以後纔可使用。請本身去搜步驟
三、給域名綁定服務器ip,不支持+端口的綁定。故域名默認指向網站80端口
四、給網站綁定域名。截圖以下:
五、綁定以後,就能夠直接訪問域名方式訪問到網站
六、在微信公衆號後臺中去綁定域名
階段四:將指定網頁生成爲二維碼
一、複製網站地址,在「草料二維碼」生成器中生成本身二維碼,保存二維碼爲圖片。
二、在微信素材管理中添加二維碼圖片,並在「圖文消息」那篇文字最後放置二維碼而後保存素材
結果:以上階段完成後,將微信公衆號中對應菜單分享給其餘朋友就達到咱們需求想要的效果.效果以下: