Example #1
0
        public IWxAuthorization GetWxAuth(IWxLoginUser loginUser)
        {
            IMiniprogram program = WxUtil.Miniprogram;
            var          request = WxUtil.GenerateWxAuthRequestUrl(program.AppId, loginUser.Code, program.AppSecrect);
            var          auth    = request.GetResponseForJson <WeChatAuthorization>();

            return(auth);
        }
Example #2
0
        //微信
        private string WxPay(string uid, decimal money)
        {
            UserFinancialManager ufm    = new UserFinancialManager();
            Hashtable            hashuf = new Hashtable();

            hashuf["ID"]            = CommonHelper.GetGuid;
            hashuf["UserID"]        = uid;
            hashuf["OrderNum"]      = SiteHelper.GenerateOrderNum();
            hashuf["OrderPayID"]    = SiteHelper.GeneratePayID();
            hashuf["ChangesAmount"] = money;
            hashuf["ChangesTime"]   = SiteHelper.GetWebServerCurrentTime();
            hashuf["ChangesType"]   = (int)UserFinancialChangesType.Recharge;
            hashuf["Remark"]        = "用户充值";
            hashuf["Operator"]      = uid;
            hashuf["OperatorType"]  = (int)UserFinancialOperatorType.User;
            hashuf["OperatorWay"]   = (int)UserFinancialOperatorWay.WeixinPubPay;
            hashuf["State"]         = (int)UserFinancialState.NewSubmit;
            bool isSuccess = ufm.AddOrEditUserFinancialInfo(hashuf, null);

            if (isSuccess)
            {
                Hashtable uf = ufm.GetUserFinancialPayInfoByPayID(hashuf["OrderPayID"].ToString());
                if (uf == null)
                {
                    return(SiteHelper.GetJsonFromHashTable(null, "faild", "生成支付订单失败"));
                }
                else
                {
                    WxUtil wxUtil = new WxUtil();
                    string prepayid = "", sign = "";
                    prepayid = wxUtil.GetPrepayId(hashuf["OrderPayID"].ToString(), "余额充值", money, weixinNotifyUrl, ip, openID);
                    Hashtable result = new Hashtable();
                    result["PayWay"]    = payway;
                    result["appId"]     = WxConfig.AppId;
                    result["timeStamp"] = wxUtil.genTimeStamp();
                    result["nonceStr"]  = wxUtil.genNonceStr();
                    result["package"]   = "prepay_id=" + prepayid;
                    result["signType"]  = "MD5";

                    SortedDictionary <string, string> dic = new SortedDictionary <string, string>();
                    dic.Add("appId", result["appId"].ToString());
                    dic.Add("timeStamp", result["timeStamp"].ToString());
                    dic.Add("nonceStr", result["nonceStr"].ToString());
                    dic.Add("package", result["package"].ToString());
                    dic.Add("signType", result["signType"].ToString());
                    sign = wxUtil.getSign(dic);

                    result["sign"] = sign;
                    Logger.Info("RechargePay,WxPay prepayId:" + result["prepayId"]);
                    return(SiteHelper.GetJsonFromHashTable(result, "success", "生成支付订单成功", "RechargePay"));
                }
            }
            else
            {
                return(SiteHelper.GetJsonFromHashTable(null, "faild", "生成支付订单失败"));
            }
        }
Example #3
0
        //https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025062

        public WxSession CreateWxSession(IWxLoginUser loginUser)
        {
            IMiniprogram program = WxUtil.Miniprogram;
            var          request = WxUtil.GenerateWxAuthRequestUrl(program.AppId, loginUser.Code, program.AppSecrect);

            var auth       = request.GetResponseForJson <WeChatAuthorization>();
            var wechatUser = Decrypt(loginUser.Data, loginUser.IV, auth.SessionKey);

            return(new WxSession()
            {
                LoginUser = loginUser, Miniprogram = program, WeCharUser = wechatUser, Authorization = auth
            });
        }
Example #4
0
 public void CreatedMemberCard(string token)
 {
     var request = WxUtil.GenerateWxCreateCardUrl(token);
     var context = request.GetResponse((http) =>
     {
         http.Method      = "POST";
         http.ContentType = "application/json; encoding=utf-8";
         var data         = File.ReadAllText("/bin/json/MemberCard.json");
         using (var stream = http.GetRequestStream())
         {
             var buffers = UTF8Encoding.UTF8.GetBytes(data);
             stream.Write(buffers, 0, buffers.Length);
             stream.Flush();
         }
         return(http);
     });
 }
Example #5
0
 public void CreateTestwhiteList(string token)
 {
     var request = WxUtil.GenerateWxtestwhitelist(token);
     var context = request.GetResponse((http) =>
     {
         http.Method      = "POST";
         http.ContentType = "application/json; encoding=utf-8";
         var data         = new
         {
             openid   = new string[] { },
             username = new string[] { "s66822351" }
         };
         using (var stream = http.GetRequestStream())
         {
             var buffers = UTF8Encoding.UTF8.GetBytes(data.ToJson());
             stream.Write(buffers, 0, buffers.Length);
             stream.Flush();
         }
         return(http);
     });
 }
Example #6
0
        public void PostLogImage(string token)
        {
            var request = WxUtil.GenerateWxUploaMediaUrl(token);
            var context = request.GetResponse((http) =>
            {
                http.Method      = "POST";
                http.ContentType = "application/x-www-form-urlencoded";
                CookieContainer cookieContainer = new CookieContainer();
                http.CookieContainer            = cookieContainer;
                http.AllowAutoRedirect          = true;
                http.Method              = "POST";
                string boundary          = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                http.ContentType         = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes  = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                StringBuilder sbHeader =
                    new StringBuilder(
                        string.Format(
                            "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                            @"yovip.jpg"));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(@"D:\Workspaces\yovip\portals\yovip.api\Content\images\yovip.jpg", FileMode.Open, FileAccess.Read);
                byte[] bArr   = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                using (Stream postStream = http.GetRequestStream())
                {
                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                    postStream.Write(bArr, 0, bArr.Length);
                    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    postStream.Flush();
                }
                return(http);
            });
        }
Example #7
0
        public QRCodeWxResponse CreateWxQRCode(string token, string cardid)
        {
            var request = WxUtil.GenerateWxQRCodeUrl(token);

            var qrcode = request.GetResponseForJson <QRCodeWxResponse>((http) =>
            {
                http.Method      = "POST";
                http.ContentType = "application/json; encoding=utf-8";
                var data         = new
                {
                    action_name    = "QR_CARD",
                    expire_seconds = 1800,
                    action_info    = new
                    {
                        card = new
                        {
                            card_id        = cardid,
                            code           = "",
                            openid         = "",
                            is_unique_code = false,
                            outer_str      = "13b",
                        }
                    }
                };
                using (var stream = http.GetRequestStream())
                {
                    var buffers = UTF8Encoding.UTF8.GetBytes(data.ToJson());
                    stream.Write(buffers, 0, buffers.Length);
                    stream.Flush();
                }
                return(http);
            });

            //{ "errcode":0,"errmsg":"ok","ticket":"gQGX7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyMkZNbVVqeHlkb2oxU1dfRWhxNGwAAgSyeOhaAwQIBwAA","expire_seconds":1800,"url":"http:\/\/weixin.qq.com\/q\/022FMmUjxydoj1SW_Ehq4l","show_qrcode_url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQGX7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyMkZNbVVqeHlkb2oxU1dfRWhxNGwAAgSyeOhaAwQIBwAA"}
            return(qrcode);
        }
Example #8
0
        /// <summary> 线程任务 </summary>
        private void run()
        {
            //初始化cookie容器
            mCookieContainer = new CookieContainer();


            //获取微信登录随机设备Id
            string deviceId = WxUtil.GetRandomDeviceId();

#if Debug
            Console.WriteLine("WxTask login device id = " + deviceId);
#endif


            //获取登录uid------------------------------------------
            WxLoginUidResult loginUidResult = executeLoginUidHttpTask();
#if Debug
            Console.WriteLine("WxTask login uid = " + (loginUidResult == null ? "null" : loginUidResult.Uid));
#endif
            if (!syncCheckLoginingState())
            {
                return;
            }

            //检测uid
            if (!WxResultUtil.CheckLoginUidResult(loginUidResult))
            {
                callbackLoginFailed(WxLoginCode.UID_ERROR);
                return;
            }


            //获取微信登录二维码-----------------------------------------------
            byte[] qrCodeBytes = executeLoginQrCodeHttpTask(loginUidResult.Uid);
#if Debug
            Console.WriteLine("WxTask login qrcode = " + (qrCodeBytes == null ? "null" : "has qr code"));
#endif
            if (!syncCheckLoginingState())
            {
                return;
            }

            if (qrCodeBytes == null)
            {
                callbackLoginFailed(WxLoginCode.QRCODE_ERROR);
                return;
            }
            //二维码回调
            OnWxTaskLoginQrCodeHandler?.Invoke(qrCodeBytes);



            //检测扫描登录-----------------------------------------------------------------
            WxLoginScanResult loginScanResult = executeLoginScanHttpTask(loginUidResult.Uid);
#if Debug
            Console.WriteLine("WxTask login scan = " + (loginScanResult == null ? "null" : loginScanResult.ToString()));
#endif
            if (!syncCheckLoginingState())
            {
                return;
            }

            if (!WxResultUtil.CheckLoginScanResult(loginScanResult))
            {
                if (WxResultUtil.CheckLoginScanExpired(loginScanResult))
                {
                    callbackLoginFailed(WxLoginCode.SCAN_EXPIRED);
                }
                else
                {
                    callbackLoginFailed(WxLoginCode.SCAN_ERROR);
                }

                return;
            }


            //开始登录操作回调-----------------------------------
            OnWxTaskLoginPreHandler?.Invoke();


            //登录步骤完成,已获取各种唯一标识符,如果该步完成,手机端显示已登录--------------------------
            WxLoginIdsResult loginIdsResult = executeLoginRedirectUriHttpTask(loginScanResult.RedirectUri);
#if Debug
            Console.WriteLine("WxTask login ids = " + (loginIdsResult == null ? "null" : loginIdsResult.ToString()));
#endif
            //设置全局host
            if (WxResultUtil.CheckLoginIdsResult(loginIdsResult))
            {
                setHost(loginIdsResult.RouteHost);
            }

            if (!syncCheckLoginingState())
            {
                if (WxResultUtil.CheckLoginIdsResult(loginIdsResult))
                {
                    executeLogout(GetHost(), loginIdsResult.Skey, loginIdsResult.Uin, loginIdsResult.Sid);
                }

                return;
            }

            if (!WxResultUtil.CheckLoginIdsResult(loginIdsResult))
            {
                if (WxResultUtil.CheckLoginIdsAccountClosure(loginIdsResult))/*loginIdsResult != null && loginIdsResult.IsAccountException()*/
                {
                    callbackLoginFailed(WxLoginCode.IDS_ACCOUNT_CLOSURE);
                }
                else
                {
                    callbackLoginFailed(WxLoginCode.IDS_ERROR);
                }

                return;
            }


            //访问初始化接口,这里面才有昵称--------------------------------------------------------
            WxLoginInitResult loginInitResult = executeLoginInitHttpTask(GetHost(), loginIdsResult, deviceId);
#if Debug
            Console.WriteLine("WxTask login init = " + (loginInitResult == null ? "null" : loginInitResult.ToString()));
#endif
            if (!syncCheckLoginingState())
            {
                executeLogout(GetHost(), loginIdsResult.Skey, loginIdsResult.Uin, loginIdsResult.Sid);
                return;
            }

            if (!WxResultUtil.CheckResultSuccess(loginInitResult))
            {
                callbackLoginFailed(WxLoginCode.INIT_ERROR);
                executeLogout(GetHost(), loginIdsResult.Skey, loginIdsResult.Uin, loginIdsResult.Sid);
                return;
            }


            //创建登录账号对象--------------------------------------------------------
            WxAccount wxAccount = WxUtil.CreateWxAccount(loginIdsResult, loginInitResult, deviceId);


            //标记登录状态
            syncSetLoginState(STATE_LOGINED);


            //发送状态通知消息,一定要发
            if (syncCheckLoginInState())
            {
                executeStatusNotifyHttpTask(GetHost(), wxAccount);
            }


            //微信登录成功回调
            OnWxTaskLoginSuccessHandler?.Invoke(wxAccount);


            //微信初始化回调
            OnWxTaskLoginInitHandler?.Invoke(wxAccount, loginInitResult);


            //获取所有联系人,一定要先获取
            if (syncCheckLoginInState())
            {
                WxContactAllResult contactAllResult = executeGetContactAllHttpTask(GetHost(), wxAccount);
                if (WxResultUtil.CheckResultSuccess(contactAllResult) && syncCheckLoginInState())
                {
                    OnWxTaskLoginGetContactAllHandler?.Invoke(wxAccount, contactAllResult.MemberList);
                }
            }


            //开始循环同步消息
            int syncCode = WxResultCode.ACCOUNT_OFFLINE;
            if (syncCheckLoginInState())
            {
                syncCode = executeSyncMsgLoop(GetHost(), wxAccount, loginInitResult.SyncKey);
            }


            //先给登出回调,再做登出请求操作
            WxLogoutCode code = syncGetLogoutCode(syncCode);
            OnWxTaskLogoutHandler?.Invoke(wxAccount, code);
            string result = executeLogout(GetHost(), wxAccount);

#if Debug
            Console.WriteLine("WxTask logout WxLogoutCode = " + code + ", nickName=" + wxAccount.NickName);
#endif
        }
Example #9
0
        //微信
        private string WxPay(string uid, decimal money)
        {
            UserFinancialManager ufm    = new UserFinancialManager();
            Hashtable            hashuf = new Hashtable();

            hashuf["ID"]            = CommonHelper.GetGuid;
            hashuf["UserID"]        = uid;
            hashuf["OrderNum"]      = SiteHelper.GenerateOrderNum();
            hashuf["OrderPayID"]    = SiteHelper.GeneratePayID();
            hashuf["ChangesAmount"] = money;
            hashuf["ChangesTime"]   = SiteHelper.GetWebServerCurrentTime();
            hashuf["ChangesType"]   = (int)UserFinancialChangesType.Recharge;
            hashuf["Remark"]        = "用户充值";
            hashuf["Operator"]      = uid;
            hashuf["OperatorType"]  = (int)UserFinancialOperatorType.User;
            hashuf["OperatorWay"]   = (int)UserFinancialOperatorWay.WeixinPay;
            hashuf["State"]         = (int)UserFinancialState.NewSubmit;
            bool isSuccess = ufm.AddOrEditUserFinancialInfo(hashuf, null);

            if (isSuccess)
            {
                Hashtable uf = ufm.GetUserFinancialPayInfoByPayID(hashuf["OrderPayID"].ToString());
                if (uf == null)
                {
                    return(SiteHelper.GetJsonFromHashTable(null, "faild", "生成支付订单失败"));
                }
                else
                {
                    WxUtil wxUtil = new WxUtil();
                    string prepayid = "", sign = "";
                    prepayid = wxUtil.GetPrepayId(hashuf["OrderPayID"].ToString(), "余额充值", money, weixinNotifyUrl, HttpContext.Current.Request.UserHostAddress);
                    Hashtable result = new Hashtable();
                    result["PayWay"]       = payway;
                    result["appId"]        = pay.wxpay.WxConfig.AppId;
                    result["partnerId"]    = pay.wxpay.WxConfig.MchId;
                    result["prepayId"]     = prepayid;
                    result["packageValue"] = "Sign=WXPay";
                    result["nonceStr"]     = wxUtil.genNonceStr();
                    result["timeStamp"]    = wxUtil.genTimeStamp();

                    SortedDictionary <string, string> dic = new SortedDictionary <string, string>();
                    dic.Add("appid", result["appId"].ToString());
                    dic.Add("noncestr", result["nonceStr"].ToString());
                    dic.Add("package", result["packageValue"].ToString());
                    dic.Add("partnerid", result["partnerId"].ToString());
                    dic.Add("prepayid", result["prepayId"].ToString());
                    dic.Add("timestamp", result["timeStamp"].ToString());
                    sign = wxUtil.getSign(dic);

                    result["sign"] = sign;
                    Logger.Info("RechargePay,WxPay prepayId:" + result["prepayId"]);

                    ICache   cache = CacheFactory.GetCache();
                    DateTime dt    = DateTime.Now.AddSeconds(5);
                    cache.Set(cacheKey, uid, dt - DateTime.Now);
                    cache.Dispose();

                    return(SiteHelper.GetJsonFromHashTable(result, "success", "生成支付订单成功", "RechargePay"));
                }
            }
            else
            {
                return(SiteHelper.GetJsonFromHashTable(null, "faild", "生成支付订单失败"));
            }
        }
Example #10
0
 public void CreatedCard(string token)
 {
     var request = WxUtil.GenerateWxCreateCardUrl(token);
     var context = request.GetResponse((http) =>
     {
         http.Method      = "POST";
         http.ContentType = "application/json; encoding=utf-8";
         var data         = new
         {
             card = new
             {
                 card_type = "GROUPON",
                 groupon   = new
                 {
                     base_info = new
                     {
                         logo_url      = @"http://mmbiz.qpic.cn\mmbiz_jpg\EEMV7pCMmetWLAjhFtj2K5kdy5sK8z6hdlQbTe0ibtfIlZhibuKoAibe5dhA1VReGWPzz7vHcQExQSicKWrMicicND0A\0",
                         brand_name    = "Joey's shop",
                         code_type     = "CODE_TYPE_TEXT",
                         title         = "132元双人火锅套餐",
                         sub_title     = "周末狂欢必备",
                         color         = "Color010",
                         notice        = "使用时向服务员出示此券",
                         service_phone = "13961576298",
                         description   = "不可与其他优惠同享如需团购券发票,请在消费时向商户提出店内均可使用,仅限堂食",
                         date_info     = new
                         {
                             type             = "DATE_TYPE_FIX_TERM",
                             fixed_term       = 15,
                             fixed_begin_term = 0
                         },
                         sku = new
                         {
                             quantity = 10000
                         },
                         get_limit        = 3,
                         use_custom_code  = false,
                         bind_openid      = false,
                         can_share        = true,
                         can_give_friend  = true,
                         location_id_list = new[]
                         {
                             123,
                             12321,
                             345345
                         },
                         custom_url_name      = "立即使用",
                         custom_url           = "https://www.baidu.com",
                         custom_url_sub_title = "6个汉字",
                         promotion_url_name   = "更多优惠",
                         promotion_url        = "https://www.163.com"
                     },
                     deal_detail = "dddddddd"
                 }
             }
         };
         using (var stream = http.GetRequestStream())
         {
             var buffers = UTF8Encoding.UTF8.GetBytes(data.ToJson());
             stream.Write(buffers, 0, buffers.Length);
             stream.Flush();
         }
         return(http);
     });
 }
Example #11
0
        public IWxAccessToken GetWxAccessToken(string appid, string secret)
        {
            var request = WxUtil.GenerateWxTokenRequestUrl(appid, secret);

            return(request.GetResponseForJson <WxAccessToken>());
        }