码迷,mamicode.com
首页 > 微信 > 详细

简单的企业微信开发 前后端

时间:2019-02-26 13:30:30      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:null   .json   vue   ebe   uek   取数据   更新   api   导致   

涉及公司内容已删除

token等票据落地设置请自行百度

 

using DAL;

using System;

using System.Collections;

using System.Collections.Generic;

using System.Data;

using System.IO;

using System.Linq;

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) {

                // 回调

                //1、发起申请申请时后,审批状态发生变化时

                //2、发起申请申请时后,在“审批中”状态,有任意审批人进行审批操作时

                //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>

 

简单的企业微信开发 前后端

标签:null   .json   vue   ebe   uek   取数据   更新   api   导致   

原文地址:https://www.cnblogs.com/zhangsonglin/p/10436533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!