测试公众号服务器配置c#
2017-08-02 18:29:48 hangyejiadao 阅读数 389
 public string CheckSign()
        {
            var httpMethod = Request.HttpMethod.ToLower();
            string httpString = string.Empty;
            if (httpMethod == "get")
            {
                httpString = Request.QueryString.ToString();
            }
            else if (httpMethod == "post")
            {
                httpMethod = Request.Form.ToString();
            }
            else
            {
                httpMethod = "请求方式不是get和post";
            }
            var strSignature = Request["signature"];
            var strEchostr = Request["echostr"];
            var strToken = "hangye";
            var strTimestamp = Request["timestamp"];
            var strNonce = Request["nonce"];
 

            //step1:字典序排序
            string[] array = new[] { strToken, strTimestamp, strNonce };
            Array.Sort(array);
          

            //step2:sha1加密
            var strResult = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Concat(array), "SHA1").ToLower();
             

            //step3:加密后的字符串与参数signature值比较
            if (strResult == strSignature.ToLower())
            { 
                return strEchostr;
            } 
            return string.Empty;
        }

2018-09-13 17:19:54 qwt7896541230 阅读数 480

先做最简单的公众号支付,也就是微信内支付。相关链接:公众号支付

Created with Raphaël 2.1.2发起支付已有OpenId?统一下单拉起WeixinJSBridge对象支付成功?支付回调结束 获取OpenId yesnoyesno

大概就这样把,还算是比较简单的,前端发起支付有WeixinJSBridge的getBrandWCPayRequest 和 wx.choosewxpay 两种方法,似乎最开始是前者,然后变成后者,最后又发现前者好用,也不知道什么情况,反正以最新官网为准把。

获取OpenId方法类

public class Authentication
    {
        /// <summary>
        /// openid用于调用统一下单接口
        /// </summary>
        public string openid { get; set; }

        /// <summary>
        /// access_token用于获取收货地址js函数入口参数
        /// </summary>
        public string access_token { get; set; }

        /// <summary>
        /// 重定向后会带上state参数,该项目用于记录跳转的URL
        /// </summary>
        public string state { get; set; }

        /**
        * 
        * 网页授权获取用户基本信息的全部过程
        * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
        * 第一步:利用url跳转获取code
        * 第二步:利用code去获取openid和access_token
        * 
        */
        public void GetOpenidAndAccessToken(Page page, string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(page.Request.QueryString["code"]))
            {
                //获取code码,以获取openid和access_token
                string code = page.Request.QueryString["code"];
                //Log.Debug(this.GetType().ToString(), "Get code : " + code);
                GetOpenidAndAccessTokenFromCode(code);

                //获取state
                state = page.Request.QueryString["state"];
            }
            else
            {
                //构造网页授权获取code的URL
                string host = page.Request.Url.Host;
                string path = page.Request.Path;
                string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);


                WxPayData data = new WxPayData();
                data.SetValue("appid", Config.AppID);
                data.SetValue("redirect_uri", redirect_uri);
                data.SetValue("response_type", "code");
                data.SetValue("scope", "snsapi_base");
                data.SetValue("state", returnUrl + "#wechat_redirect");
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
                //Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
                try
                {
                    //触发微信返回code码         
                    page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                }
            }
        }


        /**
        * 
        * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下:
        * {
        *  "access_token":"ACCESS_TOKEN",
        *  "expires_in":7200,
        *  "refresh_token":"REFRESH_TOKEN",
        *  "openid":"OPENID",
        *  "scope":"SCOPE",
        *  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        * }
        * 其中access_token可用于获取共享收货地址
        * openid是微信支付jsapi支付接口统一下单时必须的参数
        * 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
        * @失败时抛异常WxPayException
        */
        public void GetOpenidAndAccessTokenFromCode(string code)
        {
            try
            {
                //构造获取openid及access_token的url
                WxPayData data = new WxPayData();
                data.SetValue("appid", Config.AppID);
                data.SetValue("secret", Config.AppSecret);
                data.SetValue("code", code);
                data.SetValue("grant_type", "authorization_code");
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

                //请求url以获取数据
                string result = HttpService.Get(url);

                //Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result);

                JObject jd = JObject.Parse(result);
                //获取access_token
                access_token = (string)jd["access_token"];

                //获取用户openid
                openid = (string)jd["openid"];

                //Log.Debug(this.GetType().ToString(), "Get openid : " + openid);
                //Log.Debug(this.GetType().ToString(), "Get access_token : " + access_token);
            }
            catch (Exception ex)
            {
                //Log.Error(this.GetType().ToString(), ex.ToString());
                throw new Exception(ex.ToString());
            }
        }
    }

公众号支付方法类

public class JsApiPay
    {
        /**
        * 调用统一下单,获得下单结果
        * @return 统一下单结果
        * @失败时抛异常WxPayException
        */
        public WxPayData GetUnifiedOrderResult(UnifiedOrderModel unifiedOrderModel, string openid)
        {
            //统一下单
            WxPayData data = new WxPayData();
            data.SetValue("body", unifiedOrderModel.body);
            data.SetValue("attach", unifiedOrderModel.attach);
            data.SetValue("out_trade_no", unifiedOrderModel.out_trade_no);
            data.SetValue("total_fee", unifiedOrderModel.total_fee);
            data.SetValue("time_start", unifiedOrderModel.time_start);
            data.SetValue("time_expire", unifiedOrderModel.time_expire);
            data.SetValue("goods_tag", unifiedOrderModel.goods_tag);
            //交易类型,JSAPI 公众号支付, NATIVE 扫码支付, APP APP支付
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", openid);

            WxPayData result = WxPayApi.UnifiedOrder(data);
            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                //Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new Exception("UnifiedOrder response error!");
            }

            //unifiedOrderResult = result;
            return result;
        }

        /**
        *  
        * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数,
        * 微信浏览器调起JSAPI时的输入参数格式如下:
        * {
        *   "appId" : "",     //公众号名称,由商户传入     
        *   "timeStamp":" 1395712654",         //时间戳,自1970年以来的秒数     
        *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串     
        *   "package" : "prepay_id=u802345jgfjsdfgsdg888",     
        *   "signType" : "MD5",         //微信签名方式:    
        *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
        * }
        * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用
        * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
        * 
        */
        public WxPayData GetJsApiParameters(WxPayData unifiedOrderResult)
        {
            //Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            WxPayData jsApiParam = new WxPayData();
            jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

            //Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return jsApiParam;
        }


        /**
        * 
        * 获取收货地址js函数入口参数,详情请参考收货地址共享接口:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_9
        * @return string 共享收货地址js函数需要的参数,json格式可以直接做参数使用
        */
        public string GetEditAddressParameters(string url, string access_token)
        {
            string parameter = "";
            try
            {
                //string host = page.Request.Url.Host;
                //string path = page.Request.Path;
                //string queryString = page.Request.Url.Query;
                ////这个地方要注意,参与签名的是网页授权获取用户信息时微信后台回传的完整url
                //string url = "http://" + host + path + queryString;

                //构造需要用SHA1算法加密的数据
                WxPayData signData = new WxPayData();
                signData.SetValue("appid", Config.AppID);
                signData.SetValue("url", url);
                signData.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
                signData.SetValue("noncestr", WxPayApi.GenerateNonceStr());
                signData.SetValue("accesstoken", access_token);
                string param = signData.ToUrl();

                //Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param);
                //SHA1加密
                string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
                //Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign);

                //获取收货地址js函数入口参数
                WxPayData afterData = new WxPayData();
                afterData.SetValue("appId", Config.AppID);
                afterData.SetValue("scope", "jsapi_address");
                afterData.SetValue("signType", "sha1");
                afterData.SetValue("addrSign", addrSign);
                afterData.SetValue("timeStamp", signData.GetValue("timestamp"));
                afterData.SetValue("nonceStr", signData.GetValue("noncestr"));

                //转为json格式
                parameter = afterData.ToJson();
                //Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter);
            }
            catch (Exception ex)
            {
                //Log.Error(this.GetType().ToString(), ex.ToString());
                throw new Exception(ex.ToString());
            }

            return parameter;
        }
    } 

获取OpenId的中间页cs代码

public partial class WCAuth : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Authentication wcAuth = new Authentication();
                try
                {
                    //Encode后的URL
                    string returnUrl = this.Request.QueryString["returnUrl"];

                    //调用【网页授权获取用户信息】接口获取用户的openid和access_token
                    wcAuth.GetOpenidAndAccessToken(this, returnUrl);

                    Session["openid"] = wcAuth.openid;
                    Session["access_token"] = wcAuth.access_token;

                    if (!string.IsNullOrWhiteSpace(wcAuth.state))
                    {
                        wcAuth.state = HttpUtility.UrlDecode(wcAuth.state);

                        this.Response.Redirect(wcAuth.state);
                    }

                }
                catch (Exception)
                {
                    Response.Write("<span style='color:#FF0000;font-size:20px'>" + "页面加载出错,请重试" + "</span>");
                }
            }
        }
    }
function jsApiPay() {
            $.ajax({
                type: "post",
                url: "url",
                dataType: "json",
                data: {
                    "method": "GetJsApiParameters",
                    "body": $("#body").val(),
                    "attach": $("#attach").val(),
                    "out_trade_no": $("#out_trade_no").val(),
                    "total_fee": $("#total_fee").val(),
                    "goods_tag": $("#goods_tag").val()
                },
                success: function (data) {
                    var item = eval(data); //转换成json对象访问           
                    alert(data.package);

                    jsApiCall(data);

                    return;
                }
            });
        }

        //调用微信JS api 支付
        function jsApiCall(data) {
            WeixinJSBridge.invoke(
                   'getBrandWCPayRequest', {
                       "appId": data.appId,     //公众号名称,由商户传入     
                       "timeStamp": data.timeStamp,         //时间戳,自1970年以来的秒数     
                       "nonceStr": data.nonceStr, //随机串     
                       "package": data.package,
                       "signType": data.signType,         //微信签名方式:     
                       "paySign": data.paySign //微信签名 
                   },
                    function (res) {
                        WeixinJSBridge.log(res.errMsg);
                        alert(res.errCode + res.errDesc + res.errMsg);
                        alert(res.err_code + res.err_desc + res.err_msg);

                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            // 使用以上方式判断前端返回,微信团队郑重提示:
                            //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
                            alert("微信支付成功!");
                            //TODO:自行调用OrderQuery判断状态

                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                            alert("用户取消支付!");
                        } else {
                            alert("支付失败!");
                        }
                    }
            );
        }

        function callpay() {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }
                else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }
            else {
                jsApiPay();
            }
        }

遇到几个经常出现的错误:
redirect_url参数错误 网页授权问题。进入微信公众平台,点击左侧菜单“接口权限”,在右侧“网页授权 ”中找到“网页授权获取用户基本信息”,点击最右侧的修改,把网址写进去即可,注意不要加http。

no permission to execute 微信支付的开发配置中的测试授权目录或授权目录没有设置正确,去微信支付那设置下就行

还有一个是什么什么permission来着,不记得了,反正就是支付页调用不起来,这个得在微信里面实际操作才行,PC端微信,微信开发者工具等等通通不行。

2018-08-01 09:28:25 qb170217 阅读数 744

微信开放平台 公众号第三方平台开发 教程

https://blog.csdn.net/zhangdaiscott/article/details/47019753

 

公众号第三方平台系列

http://www.cnblogs.com/iCoffee/p/4813558.html

测试C#
2009-08-21 09:34:00 JFlyer 阅读数 313

  

c# 测试
2013-07-03 11:27:00 weixin_34204722 阅读数 16
string input = "//a/@href ";
            int index = input.IndexOf("/@");
            String attr = input.Substring(index+2);
            Console.WriteLine("attr=@href");

 

ArrayOf 
<ArrayOfTileResourceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <TileResourceInfo> <TileMatrixMin>17</TileMatrixMin> <TileMatrixMax>17</TileMatrixMax> <LatMin>36.03515625</LatMin> <LatMax>42.626953125</LatMax> <LonMin>113.433837890625</LonMin> <LonMax>119.8828125</LonMax> <City>***</City> <TileType>***</TileType> <Style>dom</Style> <TileMatrixSet>Matrix_0</TileMatrixSet> <Layer>dom</Layer> <Format>image/tile</Format> <Uri>http://110.249.157.236/domTile/wmts</Uri> </TileResourceInfo> <TileResourceInfo> <TileMatrixMin>17</TileMatrixMin> <TileMatrixMax>17</TileMatrixMax> <LatMin>27.037353515625</LatMin> <LatMax>32.0</LatMax> <LonMin>117.1636962890625</LonMin> <LonMax>123.189697265625</LonMax> <City>*****</City> <TileType>****</TileType> <Style>ZJDOM2W1</Style> <TileMatrixSet>Matrix_0</TileMatrixSet> <Layer>**********</Layer> <Format>image/tile</Format> <Uri>******************</Uri> </TileResourceInfo> </ArrayOfTileResourceInfo>

 

Type type = typeof(T);
            T ass = (T)Assembly.GetAssembly(type).CreateInstance(type.FullName);

            XmlDocument xdResult = new XmlDocument();
            XmlDeclaration dec = xdResult.CreateXmlDeclaration("1.0", null, null);
            xdResult.AppendChild(dec);
            XmlElement root = xdResult.CreateElement(type.Name);
            xdResult.AppendChild(root);

            XmlElement xe = xdResult.CreateElement("Name");
            xe.InnerText = "羊驼";
            root.AppendChild(xe);

            XmlSerializer xs = new XmlSerializer(type);
            StringReader reader=new StringReader(xdResult.OuterXml);
            T o = (T)xs.Deserialize(reader);       

 

测试C#

阅读数 32

usingSystem;usingSystem.Collections;usingSystem.Configuration;usingSystem.Data;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI....

博文 来自: JFlyer

c#测试

阅读数 94

原文https://www.cnblogs.com/shuanglu/p/8407273.html 面向对象的特性是?对面向对象的理解? 封装继承多态。面向对象:对象是事件的抽象,万物皆对象,在C#中面向是对一个类的抽象。 重写和重载的区别?重写:在父子之间重写,方法名称、返回值类型、参数列表必须相同。重载:函数名字相同,参数必须不同与返回值无关。 求一组数的最大公约...

博文 来自: u012177027

C#测试

阅读数 34

Moq测试基础说谈(一)——简介,下载

博文 来自: aa603395590

C#测试网络连接测试

阅读数 534

直接上代码,你们懂得privatevoidcheckNetConnect(){stringurl="www.baidu.com";stringstate="";Pingping=newPing();try{...

博文 来自: pp_fzp

C#微信公众号全攻略(1)--注册公众号

阅读数 1341

微信公众号--注册公众号(订阅号)

博文 来自: coldwind811201
没有更多推荐了,返回首页