Пример #1
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <param name="isDebug"></param>
        /// <param name="readyScript"></param>
        /// <param name="errorScript"></param>
        public static void Initialization(string appId, string secret, bool isDebug = false, string readyScript = null, string errorScript = null)
        {
            if (!General.IsNullable(appId))
            {
                StringBuilder javascript = new StringBuilder();
                string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                string nonceStr = General.UniqueString();

                WxParameters paras = new WxParameters();
                paras.SetValue("debug", isDebug);
                paras.SetValue("appId", appId);
                paras.SetValue("timestamp", timestamp);
                paras.SetValue("nonceStr", nonceStr);
                paras.SetValue("signature", MakeSign(appId, secret, nonceStr, timestamp));
                paras.SetValue("jsApiList", _jsApiList);

                javascript.AppendLine("(function($){");
                javascript.AppendLine("    if(typeof wx != \"undefined\"){");
                javascript.AppendLine("        wx.config(");
                javascript.AppendLine("            " + paras.ToJson());
                javascript.AppendLine("        );");
                javascript.AppendLine("        wx.ready(function(){");
                javascript.AppendLine("            " + readyScript);
                javascript.AppendLine("        });");
                javascript.AppendLine("        wx.error(function(result){");
                javascript.AppendLine("            " + errorScript);
                javascript.AppendLine("        });");
                javascript.AppendLine("    }");
                javascript.AppendLine("})(jQuery);");

                Helper.ExecScript(javascript.ToString());
            }
        }
Пример #2
0
        /// <summary>
        /// 缓存并获取调用微信公众号接口的全局唯一票据
        /// </summary>
        /// <param name="appId">设置应用的APPID</param>
        /// <param name="secret">设置应用的APPSECRET</param>
        /// <returns>如果缓存的票据有效,则返回缓存的票据字符串,否则调用接口重新获取票据信息</returns>
        public static string GetAccessToken(string appId, string secret)
        {
            HttpApplicationState apps = HttpContext.Current.Application;
            SortedDictionary<string, object> cache = null;
            string accessToken = null;

            if (apps[CACHEKEYNAME] != null)
                cache = apps[CACHEKEYNAME] as SortedDictionary<string, object>;

            if (!General.IsNullable(cache))
            {
                DateTime saveTime = Convert.ToDateTime(cache["last_save_time"]);
                int cost = (int)(DateTime.Now - saveTime).TotalSeconds;
                int expires = Convert.ToInt32(cache["expires_in"]);
                if (cost < expires)
                    accessToken = cache["access_token"].ToString();
            }

            if (General.IsNullable(accessToken))
            {
                if (!General.IsNullable(appId) && !General.IsNullable(secret))
                {
                    string url = "https://api.weixin.qq.com/cgi-bin/token";
                    WxParameters paras = new WxParameters();
                    paras.SetValue("grant_type", "client_credential");
                    paras.SetValue("appid", appId);
                    paras.SetValue("secret", secret);

                    NetClient client = new NetClient();
                    string response = client.Get(url, paras.Parameters);
                    WxParameters result = new WxParameters();

                    if (result.FromJson(response))
                    {
                        if (result.ContainsValue("access_token") && result.ContainsValue("expires_in"))
                        {
                            cache = result.Parameters;
                            cache.Add("last_save_time", DateTime.Now);
                            apps[CACHEKEYNAME] = cache;
                            accessToken = result["access_token"] as string;
                        }
                    }
                }
            }

            return accessToken;
        }
Пример #3
0
        /// <summary>
        /// 通过登录授权的验证信息凭证获取用户个人信息
        /// </summary>
        /// <param name="accessToken">设置登录授权的验证信息凭证</param>
        /// <param name="userId">设置用户唯一标识,一般为用户的OpenId,如果使用了微信的开放平台则为UnionId</param>
        /// <returns>返回授权后获取到的用户个人信息</returns>
        public static UserInfoResults GetUserInfoResults(string accessToken, string userId)
        {
            UserInfoResults results = null;

            if (!General.IsNullable(accessToken) && !General.IsNullable(userId))
            {
                string url = "https://api.weixin.qq.com/sns/userinfo?";

                WxParameters paras = new WxParameters();
                paras.SetValue("access_token", accessToken);
                paras.SetValue("openid", userId);

                NetClient client = new NetClient();
                string json = client.Get(url, paras.Parameters);
                results = UserInfoResults.Pares(json);
            }

            return results;
        }
Пример #4
0
        /// <summary>
        /// 通过code获取验证信息凭证
        /// </summary>
        /// <param name="appId">设置应用的唯一标识</param>
        /// <param name="secret">设置应用密钥,这个密钥是在微信开放平台提交应用审核通过后获得的</param>
        /// <param name="code">设置微信服务端返回的code字符串</param>
        /// <returns>返回微信服务端响应的验证信息凭证</returns>
        public static AuthorizationResults GetAccessTokenResults(string appId, string secret, string code)
        {
            AuthorizationResults results = null;

            if (!General.IsNullable(appId) && !General.IsNullable(code) && !General.IsNullable(secret))
            {
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?";

                WxParameters paras = new WxParameters();
                paras.SetValue("appid", appId);
                paras.SetValue("secret", secret);
                paras.SetValue("code", code);
                paras.SetValue("grant_type", "authorization_code");

                NetClient client = new NetClient();
                string json = client.Get(url, paras.Parameters);

                results = AuthorizationResults.Pares(json);
            }

            return results;
        }
Пример #5
0
        private static string MakeSign(string appId, string secret, string nonceStr, string timeStamp)
        {
            string ticket = GetTicket(appId, secret);
            string sign = string.Empty;

            if (!General.IsNullable(ticket))
            {
                WxParameters paras = new WxParameters();
                paras.SetValue("noncestr", nonceStr);
                paras.SetValue("jsapi_ticket", ticket);
                paras.SetValue("timestamp", timeStamp);
                paras.SetValue("url", HttpContext.Current.Request.Url.AbsoluteUri);

                string make = paras.ToQueryString();
                StringBuilder md = new StringBuilder();
                byte[] buffer = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(make));
                foreach (byte b in buffer)
                    md.Append(b.ToString("x2"));

                sign = md.ToString();
            }

            return sign;
        }
Пример #6
0
        private static string GetTicket(string appId, string secret)
        {
            HttpApplicationState apps = HttpContext.Current.Application;
            SortedDictionary<string, object> cache = null;
            string ticket = null;

            if (apps[CACHEKEYNAME] != null)
                cache = apps[CACHEKEYNAME] as SortedDictionary<string, object>;

            if (!General.IsNullable(cache))
            {
                DateTime saveTime = Convert.ToDateTime(cache["last_save_time"]);
                int cost = (int)(DateTime.Now - saveTime).TotalSeconds;
                int expires = Convert.ToInt32(cache["expires_in"]);
                if (cost < expires)
                    ticket = cache["ticket"] as string;
            }

            if (General.IsNullable(ticket))
            {
                if (!General.IsNullable(appId) && !General.IsNullable(secret))
                {
                    string accessToken = InterfaceCredentials.GetAccessToken(appId, secret);
                    string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
                    WxParameters paras = new WxParameters();
                    paras.SetValue("access_token", accessToken);
                    paras.SetValue("type", "jsapi");

                    NetClient client = new NetClient();
                    string response = client.Get(url, paras.Parameters);
                    WxParameters result = new WxParameters();

                    if (result.FromJson(response))
                    {
                        if (result.ContainsValue("ticket") && result.ContainsValue("expires_in"))
                        {
                            cache = result.Parameters;
                            cache.Remove("errcode");
                            cache.Remove("errmsg");
                            cache.Add("last_save_time", DateTime.Now);
                            apps[CACHEKEYNAME] = cache;
                            ticket = result["ticket"] as string;
                        }
                    }
                }
            }

            return ticket;
        }
Пример #7
0
        /// <summary>
        /// 使用指定的处理过程来处理微信支付结果通知的回调
        /// </summary>
        /// <param name="callBack">设置处理方法,该方法需返回一个布尔值来指示处理是否成功</param>
        public static void NotifyCall(NotifyCallBack callBack)
        {
            bool flag = true;
            OrderPayResultParameters results = OrderPayResultParameters.RequestPares();
            if (callBack != null)
                flag = callBack.Invoke(results);

            WxParameters paras = new WxParameters();
            paras.SetValue("return_code", (flag ? "SUCCESS" : "FAIL"));
            paras.SetValue("return_msg", (flag ? "OK" : "UNIFIED ORDER ERROR"));
            HttpContext.Current.Response.Write(paras.ToXML());
        }
Пример #8
0
        /// <summary>
        /// 在微信浏览器内生成公众号预支付订单
        /// </summary>
        /// <param name="reportCost">设置是否需要上报测速</param>
        /// <returns>预支付订单生成成功则返回一段JavaScript脚本,这段脚本可以在基于HTML5的客户端网页中发起微信支付流程</returns>
        public string PublicPlaceOrder(bool reportCost = false)
        {
            ResultParameters results = this.Results;

            if (PlaceOrder(PayTradeType.JSAPI, reportCost))
            {
                if (results.IsResultSuccess)
                {
                    StringBuilder js = new StringBuilder();
                    WxParameters paras = new WxParameters();
                    paras.SetValue("appId", results.AppId);
                    paras.SetValue("api_key", this.Submits.ApiKey);
                    paras.SetValue("timeStamp", Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString());
                    paras.SetValue("nonceStr", General.UniqueString());
                    paras.SetValue("package", "prepay_id=" + results.PrepayId);
                    paras.SetValue("signType", "MD5");
                    paras.SetValue("paySign", paras.MakeSign());

                    js.AppendLine("function __onWxPayBridgeReady() {");
                    js.AppendLine("    WeixinJSBridge.invoke(");
                    js.AppendLine("        \"getBrandWCPayRequest\",");
                    js.AppendLine("        " + paras.ToJson() + ",");
                    js.AppendLine("        function (result) {");
                    js.AppendLine("            if(typeof window[\"onBrandWCPayResponse\"] == \"function\") {");
                    js.AppendLine("                var __response = result.err_msg.replace(\"get_brand_wcpay_request:\",\"\");");
                    js.AppendLine("                onBrandWCPayResponse(__response, result);");
                    js.AppendLine("            }");
                    js.AppendLine("        }");
                    js.AppendLine("    );");
                    js.AppendLine("}");
                    js.AppendLine();
                    js.AppendLine("function __toggleWxPayBridge() {");
                    js.AppendLine("    if (typeof WeixinJSBridge == \"undefined\"){");
                    js.AppendLine("        if (document.addEventListener){");
                    js.AppendLine("            document.addEventListener(\"WeixinJSBridgeReady\", __onWxPayBridgeReady, false);");
                    js.AppendLine("        }");
                    js.AppendLine("        else if(document.attachEvent){");
                    js.AppendLine("            document.attachEvent(\"WeixinJSBridgeReady\", __onWxPayBridgeReady);");
                    js.AppendLine("            document.attachEvent(\"onWeixinJSBridgeReady\", __onWxPayBridgeReady);");
                    js.AppendLine("        }");
                    js.AppendLine("    }");
                    js.AppendLine("    else{");
                    js.AppendLine("        __onWxPayBridgeReady();");
                    js.AppendLine("    }");
                    js.AppendLine("}");
                    //return paras.ToJson();
                    return js.ToString();
                }
            }

            return null;
        }
Пример #9
0
        /// <summary>
        /// 获取微信服务器的IP地址列表
        /// </summary>
        /// <param name="accessToken">设置全局接口调用票据字符串</param>
        /// <returns>如果票据有效,则返回微信服务器的IP地址列表,否则返回NULL</returns>
        public static List<string> GetServerIP(string accessToken)
        {
            List<string> ipList = null;

            if (!General.IsNullable(accessToken))
            {
                string url = "https://api.weixin.qq.com/cgi-bin/getcallbackip";
                NetClient client = new NetClient();
                string response = client.Get(url, new string[] { "access_token=" + accessToken });
                WxParameters result = new WxParameters();
                if (result.FromJson(response))
                {
                    if (result.ContainsValue("ip_list"))
                        ipList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(result["ip_list"].ToString());
                }
            }

            return ipList;
        }
Пример #10
0
        /// <summary>
        /// 使当前第三方站点跳转到微信授权URI地址,并获取Code
        /// </summary>
        /// <param name="appId">设置微信应用的唯一标识</param>
        /// <param name="redirectUri">设置授权后重定向的回调链接地址,如果不设置则默认使用当前第三方站点的当前URL</param>
        /// <param name="scope">设置应用授权作用域</param>
        /// <param name="state">设置自定义的状态参数,如果不设置,则默认情况下生成一个字符串</param>
        public static void RedirectConnectCode(string appId, string redirectUri, string scope, string state = null)
        {
            if (!General.IsNullable(appId))
            {
                HttpResponse response = HttpContext.Current.Response;
                scope = General.ToNullable(scope, AuthorizationScope.USERINFO);
                string url = string.Format("https://open.weixin.qq.com/connect/{0}?", scope.Equals(AuthorizationScope.PCLOGIN) ? "qrconnect" : "oauth2/authorize");

                if (General.IsNullable(redirectUri))
                {
                    Uri uri = HttpContext.Current.Request.Url;
                    redirectUri = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.AbsolutePath);
                }

                WxParameters paras = new WxParameters();
                paras.SetValue("appid", appId);
                paras.SetValue("redirect_uri", HttpUtility.UrlEncode(redirectUri, Encoding.UTF8));
                paras.SetValue("response_type", "code");
                paras.SetValue("scope", scope);
                paras.SetValue("state", General.ToNullable(state, General.UniqueString()) + "#wechat_redirect");

                url += paras.ToQueryString();
                response.Redirect(url);
            }
        }