예제 #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));
            }
        }
        public static string DecryptCardCode(string encryptedCardCode)
        {
            DecryptCodeRequest decryptRequest = new DecryptCodeRequest();

            decryptRequest.EncryptedCode = encryptedCardCode;

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

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

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

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

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

            DecryptCodeResponse response = JsonTypedSerializer <DecryptCodeResponse> .Deserialize(respondText);;

            if (response.ErrorCode != 0)
            {
                throw new InvalidOperationException(string.Format("Error: {0}|{1}", response.ErrorCode, response.ErrorMessage));
            }
            return(response.Code);
        }
        /// <summary>
        /// Get Wechat Card QRCode url.
        /// </summary>
        /// <param name="cardId">Wechat Card Id</param>
        /// <param name="cardCode">Custom Card Code, optional. 20 characters.</param>
        /// <param name="isUnique">Is code unique. If true then the code can only be scanned once.</param>
        /// <returns></returns>
        public static string GetCardQRCodeUrl(string cardId, int expireSeconds, string cardCode = null, bool isUnique = true)
        {
            QRCodeRequest qrCodeRequest = new QRCodeRequest();

            qrCodeRequest.ActionName         = QRCodeRequest.ActionNames.QR_CARD.ToString();
            qrCodeRequest.ExpireSeconds      = expireSeconds;
            qrCodeRequest.ActionInfo.CardObj = new QRCodeRequest.QRCodeActionInfo.Card()
            {
                CardCode     = cardCode,
                CardId       = cardId,
                IsUniqueCode = isUnique
            };

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

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

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

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

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


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

            if (error.ErrorCode != 0)
            {
                throw new InvalidOperationException(string.Format("Error: {0}|{1}", error.ErrorCode, error.ErrorMessage));
            }

            QRCodeResponse response = JsonTypedSerializer <QRCodeResponse> .Deserialize(respondText);;

            return(string.Format(ShowQRCodeUrlTemplate, response.Ticket));
        }
        /// <summary>
        /// Get Wechat Permanant QRCode url.
        /// </summary>
        /// <param name="sceneString">Wechat Scene String, which is the text code embedded in the QR graph.</param>
        /// <returns></returns>
        public static string GetPermanantQRCodeUrl(string sceneString)
        {
            QRCodeRequest qrCodeRequest = new QRCodeRequest();

            qrCodeRequest.ActionName       = QRCodeRequest.ActionNames.QR_LIMIT_STR_SCENE.ToString();
            qrCodeRequest.ExpireSeconds    = 0;
            qrCodeRequest.ActionInfo.Scene = new QRCodeRequest.QRCodeActionInfo.QRCodeScene()
            {
                SceneString = sceneString
            };

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

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

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

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

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


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

            if (error.ErrorCode != 0)
            {
                throw new InvalidOperationException(string.Format("Error: {0}|{1}", error.ErrorCode, error.ErrorMessage));
            }

            QRCodeResponse response = JsonTypedSerializer <QRCodeResponse> .Deserialize(respondText);;

            return(string.Format(ShowQRCodeUrlTemplate, response.Ticket));
        }
예제 #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);
            }
        }