簡單的企業微信開發 先後端

涉及公司內容已刪除html

token等票據落地設置請自行百度面試

 

using DAL;算法

using System;數據庫

using System.Collections;json

using System.Collections.Generic;api

using System.Data;微信

using System.IO;app

using System.Linq;dom

using System.Net;異步

using System.Security.Cryptography;

using System.Security.Policy;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

 

namespace custServiceMange

{

    public partial class approval : System.Web.UI.Page

    {

        //AgentId 1000010

        //Secret Et58dZVUEK3AJ7w-Tb3RRYzV8VKScOHkIW3mWO1ymAU

        //agentConfig與config的簽名算法徹底同樣,可是jsapi_ticket的獲取方法不同

        //定義對象

        private string timestamp;//簽名的時間戳

        private string noncestr;//簽名的隨機串

        private string ent_signature;//企業簽名

        private string app_signature;//應用簽名

        private string ent_ticket;//企業的jsapi_ticket

        private string app_ticket;//應用的jsapi_ticket

        private string uri;//url

        public string Timestamp

        {

            get

            {

                return timestamp;

            }

            set

            {

                timestamp = value;

            }

        }

        public string Noncestr

        {

            get

            {

                return noncestr;

            }

            set

            {

                noncestr = value;

            }

        }

        public string entSignature

        {

            get

            {

                return ent_signature;

            }

            set

            {

                ent_signature = value;

            }

        }

        public string appSignature

        {

            get

            {

                return app_signature;

            }

            set

            {

                app_signature = value;

            }

        }

        public string entTicket

        {

            get

            {

                return ent_ticket;

            }

            set

            {

                ent_ticket = value;

            }

        }

        public string appTicket

        {

            get

            {

                return app_ticket;

            }

            set

            {

                ent_ticket = value;

            }

        }

        public string Uri

        {

            get

            {

                return uri;

             }

            set

            {

                uri = value;

            }

        }

      

        protected void Page_Load(object sender, EventArgs e)

        {

            //企業AccessTicket

            string entAccessTicket = GetEntAccessToken();

            ent_ticket = GetEntJsapi_Ticket(entAccessTicket);

            //企業簽名

            ent_signature = GetSignature(ent_ticket, noncestr, timestamp, uri);

 

            //應用AccessTicket

            string appAccessTicket = GetAppAccessToken();

            app_ticket = GetAppJsapi_Ticket(appAccessTicket);

            //應用簽名

            app_signature = GetSignature(app_ticket, noncestr, timestamp, uri);

 

            //簽名的時間戳

            timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);

 

            //簽名的隨機串

            noncestr = new Random().Next(10000).ToString();

 

            //本地地址

            uri = Request.Url.ToString().Replace("#", "");

 

            this.DataBind();

 

        }

 

        /// <summary>

        /// 獲取企業的AccessToken

        /// </summary>

        /// <returns></returns>

        public static string GetEntAccessToken()

        {

            //取數據庫存儲過程的AccessToken

            DataTable dt1 = DAL.DbHelper.Query("EXEC [192.168.0.11].[DB_WCWorkAccount].dbo.sp_GetWCWAAAccessToken 1").Tables[0];

            string s1_AccessToken = dt1.Rows[0]["AccessToken"].ToString().Trim();//企業的AccessToken

            return s1_AccessToken;

        }

 

        /// <summary>

        /// 獲取應用的AccessToken

        /// </summary>

        /// <returns></returns>

        public static string GetAppAccessToken()

        {

            //取數據庫存儲過程的AccessToken

            DataTable dt2 = DAL.DbHelper.Query("EXEC [192.168.0.11].[DB_WCWorkAccount].dbo.sp_GetWCWAAAccessToken 2").Tables[0];

            string s2_AccessToken = dt2.Rows[0]["AccessToken"].ToString().Trim();//應用的AccessToken

            return s2_AccessToken;

 

        }

 

        /// <summary>

        /// 獲取企業Jsapi_Ticket

        /// </summary>

        /// <returns></returns>

        public static string GetEntJsapi_Ticket(string entAccessToken)

        {

            string type = "jsapi";

            string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", entAccessToken, type);

            var wc = new WebClient();

            var strReturn = wc.DownloadString(tokenUrl); //取得微信返回的json數據

            JObject obj = JObject.Parse(strReturn);  

            string ticket = obj["strReturn"]["ticket"].ToString();

            return ticket;

        }

 

        /// <summary>

        /// 獲取應用Jsapi_Ticket

        /// </summary>

        /// <returns></returns>

        public static string GetAppJsapi_Ticket(string appAccessToken)

        {

            string type = "jsapi";

            string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", appAccessToken, type);

            var wc = new WebClient();

            var strReturn = wc.DownloadString(tokenUrl); //取得微信返回的json數據

            JObject obj = JObject.Parse(strReturn);

            string ticket = obj["strReturn"]["ticket"].ToString();

            return ticket;

        }

 

        /// <summary>

        /// 獲取JS-SDK權限驗證的簽名Signature

        /// </summary>

        /// <param name="ticket"></param>

        /// <param name="noncestr"></param>

        /// <param name="timestamp"></param>

        /// <param name="url"></param>

        /// <returns>CreateSha1(parameters)</returns>

        public static string GetSignature(string ticket, string noncestr, string timestamp, string url)

        {

            var parameters = new Hashtable();

            parameters.Add("jsapi_ticket", ticket);

            parameters.Add("noncestr", noncestr);

            parameters.Add("timestamp", timestamp);

            parameters.Add("url", url);

            return CreateSha1(parameters);

        }

 

        /// <summary>

        /// sha1加密

        /// </summary>

        /// <returns>GetSha1(sb.ToString()).ToLower()</returns>

        private static string CreateSha1(Hashtable parameters)

        {

            var sb = new StringBuilder();

            var akeys = new ArrayList(parameters.Keys);

            akeys.Sort();

 

            foreach (var k in akeys)

            {

                if (parameters[k] != null)

                {

                    var v = (string)parameters[k];

 

                    if (sb.Length == 0)

                    {

                        sb.Append(k + "=" + v);

                    }

                    else

                    {

                        sb.Append("&" + k + "=" + v);

                    }

                }

            }

            return GetSha1(sb.ToString()).ToLower();

        }

        /// <summary>

        /// 簽名算法

        /// </summary>

        /// <param name="str"></param>

        /// <returns>hash</returns>

        public static string GetSha1(string str)

        {

            //創建SHA1對象

            SHA1 sha = new SHA1CryptoServiceProvider();

            //將mystr轉換成byte[]

            ASCIIEncoding enc = new ASCIIEncoding();

            byte[] dataToHash = enc.GetBytes(str);

            //Hash運算

            byte[] dataHashed = sha.ComputeHash(dataToHash);

            //將運算結果轉換成string

            string hash = BitConverter.ToString(dataHashed).Replace("-", "");

            return hash;

        }

 

 

 

    }

}

 

 

Aspx:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="approval.aspx.cs" Inherits="custServiceMange.approval" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>審批功能</title>

</head>

<body>

 

    <table width="100%" align="center" border="0">

    <tr>

      <td>

        申請類型:

        <select neme="approveType">

          <option value ="請假">請假</option>

          <option value ="出差">出差</option>

          <option value="加班">加班</option>

          <option value="出席面試">出席面試</option>

     </select>

      </td>

  </tr>

    <tr>

        <td>

           工號:<input name="workNo" type="text" id="workId" tabindex="1" size="15" value=""/>

        </td>

    </tr>

    <tr>

       <td>

           部門:

        <select neme="department">

          <option value ="開發部">開發部</option>

          <option value ="執行部">執行部</option>

          <option value="市場部">市場部</option>

          <option value="測試部">測試部</option>

        </select>

       </td>

    </tr>

    <tr>

       <td>姓名:<input name="name" type="text" id="name" tabindex="1" size="15" value=""/></td>

    </tr>

    <tr>

        <td>

            開始時間:<input id="startTime" type="date" value=""/>

        </td>

    </tr>

    <tr>

         <td>

             結束時間:<input id="endTime" type="date" value=""/>

        </td>

    </tr>

    <tr>

      <td>

          時長

          <input id="lengthTime"  type="date" value=""/>

      </td>

    </tr>

    <tr>

       <td>

           <textarea rows="20" cols="100">申請事由</textarea>

       </td>

    </tr>

    <tr>

       <td>

           <textarea rows="20" cols="100" >附件連接</textarea>

       </td>

    </tr>

    </table>

</body>

     <%-- 步驟一:引入JS文件--%>

    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

    <%--步驟二:經過config接口注入權限驗證配置--%>

    <script>

        //config注入的是企業的身份與權限

            wx.config({

            debug: true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。

            appId: 'wwd9d5b7cf59f1e871', // 必填,公衆號的惟一標識

            timestamp: <%# Eval("timestamp") %>, // 必填,生成簽名的時間戳

            nonceStr: '<%# Eval("nonceStr") %>', // 必填,生成簽名的隨機串

            signature: '<%# Eval("ent_signature") %>',// 必填,簽名,config因此爲企業簽名

            jsApiList: ['oaType','templateId','thirdNo','extData'] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2

            });

 

 

        //oaType      操做類型,目前支持:10001-發起審批;10002-查看審批詳情。

        //templateId  發起審批的模板ID,在自建應用-審批接口中建立模板可獲取。

        //thirdNo     審批單號,由開發者自行定義,不可重複。

        //extData     詳情數據,Json格式,用於審批詳情頁信息展現。

        ////步驟三:經過ready接口處理成功驗證

        //wx.ready(function(){

        //    // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。

        //});

        ////步驟四:經過error接口處理失敗驗證

        //wx.error(function(res){

        //    // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。

        //});

 

        //agentConfig注入的是應用的身份與權限

        wx.agentConfig({

            corpid: 'wwd9d5b7cf59f1e871', // 必填,企業微信的corpid,必須與當前登陸的企業一致

            agentid: '', // 必填,企業微信的應用id

            timestamp:  <%# Eval("timestamp") %>, // 必填,生成簽名的時間戳

            nonceStr: '<%# Eval("nonceStr") %>', // 必填,生成簽名的隨機串

            signature: '<%# Eval("app_signature") %>',// 必填,簽名,agentConfig因此爲應用簽名

            jsApiList: ['oaType','templateId','thirdNo','extData'], //必填

            success: function(res) {

                // 回調

                //一、發起申請申請時後,審批狀態發生變化時

                //二、發起申請申請時後,在「審批中」狀態,有任意審批人進行審批操做時

                //oaType       操做類型,目前支持:10001-發起審批;10002-查看審批詳情。

                //templateId   發起審批的模板ID,在自建應用-審批接口中建立模板可獲取。

                //thirdNo      審批單號,由開發者自行定義,不可重複。

                //extData      詳情數據,Json格式,用於審批詳情頁信息展現。

                wx.invoke('thirdPartyOpenPage', {

                    "oaType": "10001",// String

                    "templateId": "",// String 自建應用中 審批功測試 模板編號

                    "thirdNo": "",// String

                    "extData": {

                        'fieldList': [{

                            'title': '申請類型',

                            'type': 'text',

                            'value': '',

                        },

                        {

                            'title': '工號',

                            'type': 'text',

                            'value': '',

                        },

                         {

                             'title': '部門',

                             'type': 'text',

                             'value': '',

                         },

                        {

                            'title':'姓名',

                            'type':'text',

                            'value':'',

                        },

                        {

                            'title':'開始時間',

                            'type':'text',

                            'value':'',

                        },

                         {

                             'title': '結束時間',

                             'type': 'text',

                             'value': '',

                         },

                          {

                              'title': '時長',

                              'type': '',

                              'value': '',

                          },

                        {

                            'title':'申請事由',

                            'type':'text',

                            'value':'',

                        },

                        {

                            'title':'附件連接',

                            'type':'link',

                            'value':'',

                        }]

 

                    },// JSON

                })

            },

            fail: function(res) {

                if(res.errMsg.indexOf('function not exist') > -1){

                    alert('版本太低請升級')

                }

            }

        });

    </script>

</html>

相關文章
相關標籤/搜索