Ejemplo n.º 1
0
        public string Post()
        {
            //通过code获取access_token
            string code = Request.Query["code"];
            string url  = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd001485d83e3628b&secret={WeChatConfig.APP_SECRET}&code={code}&grant_type=authorization_code";

            _logger.Info("unifiedorder->请求access_token地址为:" + url);
            var client  = new RestClient(url);
            var request = new RestRequest(Method.GET);

            request.Timeout = 10000;
            IRestResponse response = client.Execute(request);

            _logger.Info("unifiedorder->请求access_token返回内容为:" + url);
            string openid = JsonConvert.DeserializeObject <Data>(response.Content)?.openid;

            _logger.Info("获取到openid为:" + openid);
            _logger.Info("开始支付:" + url);
            url             = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            client          = new RestClient(url);
            request         = new RestRequest(Method.POST);
            request.Timeout = 10000;
            WeChatPayData payData = new WeChatPayData();

            payData.SetValue("appid", WeChatConfig.APP_ID);
            payData.SetValue("mch_id", WeChatConfig.MCH_ID);
            payData.SetValue("nonce_str", payData.GenerateNonceStr());
            payData.SetValue("body", "test");
            payData.SetValue("out_trade_no", DateTime.Now.ToString("yyyyMMddHHmmss"));
            payData.SetValue("total_fee", 1);
            payData.SetValue("spbill_create_ip", "127.0.0.1");
            payData.SetValue("notify_url", "http://hexiaodong.top/api/pay/notify_url");
            payData.SetValue("trade_type", "JSAPI");
            payData.SetValue("openid", openid);                                 //"oTSBW5wX09Qwiidfk1sarDeXq-hY"
            payData.SetValue("sign_type", WeChatPayData.SIGN_TYPE_HMAC_SHA256); //签名类型
            payData.SetValue("sign", payData.MakeSign());
            string xml = payData.ToXml();

            request.AddJsonBody(xml);
            response = client.Execute(request);
            payData.FromXml(response.Content);
            WeChatPayData jsApiParam = new WeChatPayData();

            jsApiParam.SetValue("appId", WeChatConfig.APP_ID);
            jsApiParam.SetValue("timeStamp", jsApiParam.GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", jsApiParam.GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + payData.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", WeChatPayData.SIGN_TYPE_HMAC_SHA256);
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());
            return(jsApiParam.ToJson());
        }