1. 程式人生 > >C#微信支付(二)—— 公眾號支付

C#微信支付(二)—— 公眾號支付

先做最簡單的公眾號支付,也就是微信內支付。相關連結:公眾號支付

大概就這樣把,還算是比較簡單的,前端發起支付有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端微信,微信開發者工具等等通通不行。