コード例 #1
0
        // {
        //    "touser":"******",
        //    "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
        //    "url":"http://weixin.qq.com/download",
        //    "data":{
        //            "first": {
        //                "value":"恭喜你购买成功!",
        //                "color":"#173177"
        //            },
        //            "keynote1":{
        //                "value":"巧克力",
        //                "color":"#173177"
        //            },
        //            "keynote2": {
        //                "value":"39.8元",
        //                "color":"#173177"
        //            },
        //            "keynote3": {
        //                "value":"2014年9月22日",
        //                "color":"#173177"
        //            },
        //            "remark":{
        //                "value":"欢迎再次购买!",
        //                "color":"#173177"
        //            }
        //      }
        // }
        #endregion

        public static void SendTemplateMessage(TemplateMessageRequest message)
        {
            if (message == null)
            {
                throw new InvalidOperationException("Parameter cannot be NULL.");
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(SendTemplateMsgUrlTemplate, AccessTokenData));

            request.Method      = "POST";
            request.ContentType = "application/json; charset=utf-8";
            Stream stream = request.GetRequestStream();

            string messageContent = JsonTypedSerializer <TemplateMessageRequest> .Serialize(message);

//#warning: replace with actual logic
//              "{\"data\":{\"first\":{\"color\":\"#173177\",\"value\":\"恭喜您领票成功!\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"Test 4\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"2016-3-10\"},\"keyword3\":{\"color\":\"#173177\",\"value\":\"New Location\"},\"keyword4\":{\"color\":\"#173177\",\"value\":\"A2\"},\"remark\":{\"color\":\"#173177\",\"value\":\"点击详情可查看电子票详细信息。\"}},\"template_id\":\"sm9qjFusjXOi9Pk5CwU8G_UQVlJm8RFEFZ5XJnZay3o\",\"touser\":\"oQQZHv_-vGsgcytoYhFS00sw4mOs\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdbb288aa372b8280&redirect_uri=https%3a%2f%2fgcsamplesale.nike.com%2fgcsamplesale%2fticket.aspx%3fticketid%3d220800c8-a434-4289-9446-1870c0764caa&response_type=code&scope=snsapi_base&state=#wechat_redirect\"}";

            DataContractJsonSerializer serRequest = new DataContractJsonSerializer(typeof(TemplateMessageRequest));

            serRequest.WriteObject(stream, message);
            stream.Close();

            HttpWebResponse res         = (HttpWebResponse)request.GetResponse();
            string          respondText = new StreamReader(res.GetResponseStream()).ReadToEnd();

            WechatLib.WriteLog(string.Format("Template message sent: {0}", messageContent));

            TemplateMessageRequestError error = JsonTypedSerializer <TemplateMessageRequestError> .Deserialize(respondText);

            if (error.ErrorCode != 0)
            {
                throw new InvalidOperationException(string.Format("Error: {0}|{1}", error.ErrorCode, error.MessageId));
            }
        }
コード例 #2
0
        public static string GetOAuthUrl(string appId, string redirectUriHTTPS, OAuthScope scope, string state)
        {
            string url = string.Format(OAuthUrlTemplate, appId, HttpUtility.UrlEncode(redirectUriHTTPS), scope.ToString(), state);

            WechatLib.WriteLog("OAuthUrl converted:" + url);
            return(url);
        }
コード例 #3
0
        private void HandleWechatRequest()
        {
            string method = Request.HttpMethod.ToUpper();

            WechatLib.WriteLog(method + "|" + Request.Url, DateTime.UtcNow);

            switch (method)
            {
            case "GET":
                // 微信加密签名
                string signature = Request.QueryString["signature"];
                // 时间戳
                string timestamp = Request.QueryString["timestamp"];
                // 随机数
                string nonce = Request.QueryString["nonce"];
                // 随机字符串
                string echostr = Request.QueryString["echostr"];
                if (WechatLib.CheckSignature(signature, timestamp, nonce))
                {
                    Response.ClearContent();
                    Response.ContentType = "text/plain";
                    Response.Write(echostr);
                    WechatLib.WriteLog("Echo:" + echostr, DateTime.UtcNow);
                }
                Response.End();
                break;

            case "POST":
                Response.ContentType = "application/xml";
                StreamReader      stream = new StreamReader(Request.InputStream);
                string            xml    = stream.ReadToEnd();
                WechatBaseMessage msg    = WechatBaseMessage.FromXml <WechatBaseMessage>(xml);
                WechatLib.WriteMessageLog(msg, WechatLib.MessageDirection.Inbound, xml);

                Response.ClearContent();

                WechatBaseMessage responseMsg = WechatLib.RespondMessage(msg, xml);

                if (responseMsg != null)
                {
                    responseMsg.CreateTime   = DateTime.UtcNow;
                    responseMsg.ToUserName   = msg.FromUserName;
                    responseMsg.FromUserName = msg.ToUserName;

                    string responseText = responseMsg.ToXml();
                    Response.Write(responseText);
                    WechatLib.WriteMessageLog(responseMsg, WechatLib.MessageDirection.Outbound, responseText);
                }
                Response.End();
                break;
            }
        }
コード例 #4
0
 /// <summary>
 /// Process OAuth request and parse the open id.
 /// </summary>
 private void HandleOAuthRequest()
 {
     try
     {
         WechatLib.OAuthAccessToken token = WechatLib.GetOAuthOpenIdByCode(WechatLib.AppId, WechatLib.AppSecret, Code);
         WechatOpenId = token.OpenId;
         WechatLib.WriteLog("OAuth success. OpenId=" + WechatOpenId);
     }
     catch (Exception e)
     {
         WechatOpenId = string.Empty;
         WechatLib.WriteLog("OAuth failed. " + e.ToString());
     }
 }
コード例 #5
0
        /// <summary>
        /// Get OpenId by encrypted code. The code is sent by Wechat within each OAuth request.
        /// </summary>
        /// <param name="appId">Wechat AppId</param>
        /// <param name="appSecret">Wechat AppSecret</param>
        /// <param name="code">OAuth encrypted code</param>
        /// <returns>OAuthAccess token containing the openid</returns>
        internal static OAuthAccessToken GetOAuthOpenIdByCode(string appId, string appSecret, string code)
        {
            //send code to OAuthGetAccessTokenUrl
            string         url     = string.Format(OAuthGetAccessTokenUrlTemplate, appId, appSecret, code);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";
            WechatLib.WriteLog("OAuth get access token:" + url);
            OAuthAccessToken accessToken = null;

            try
            {
                HttpWebResponse res         = (HttpWebResponse)request.GetResponse();
                string          respondText = new StreamReader(res.GetResponseStream()).ReadToEnd();
                WechatLib.WriteLog("OAuth access token received:" + respondText);

                //retrieve json and return OAuthAccessToken
                accessToken = JsonTypedSerializer <OAuthAccessToken> .Deserialize(respondText);

                if (accessToken != null)
                {
                    return(accessToken);
                }
                else
                {
                    Error error = JsonTypedSerializer <Error> .Deserialize(respondText);

                    throw new InvalidOperationException(string.Format("Error: {0}|{1}", error.ErrorCode, error.ErrorMessage));
                }
            }
            catch (Exception ex)
            {
                WechatLib.WriteLog("Get OAuth access token exception:" + ex.ToString());
                return(accessToken);
            }
        }