首先介紹一下我在調用微信支付接口使用的是 weixin.senparc SDK,非常方便好用開源的一個微信開發SDK。
weixin.senparc SDK 官網:http://weixin.senparc.com/
先去下載下來Senparc.Weixin SDK。
在調起支付接口之前,需要先要調用統一下單接口,商戶系統先調用該接口在微信支付服務后臺生成預支付交易單,返回正確的預支付交易回話標識后再在APP里面調起支付。
微信 JsApi支付 在這個目錄下 Senparc.Weixin.MP.Sample.Controllers 找到JsApi支付。
public ActionResult JsApi(string code, string state) { if (string.IsNullOrEmpty(code)) { return Content("您拒絕了授權!"); } if (!state.Contains("|")) { //這里的state其實是會暴露給客戶端的,驗證能力很弱,這里只是演示一下 //實際上可以存任何想傳遞的數據,比如用戶ID,并且需要結合例如下面的Session["OAuthAccessToken"]進行驗證 return Content("驗證失敗!請從正規途徑進入!1001"); } try { //獲取產品信息 var stateData = state.Split('|'); int productId = 0; ProductModel product = null; if (int.TryParse(stateData[0], out productId)) { int hc = 0; if (int.TryParse(stateData[1], out hc)) { var products = ProductModel.GetFakeProductList(); product = products.FirstOrDefault(z => z.Id == productId); if (product == null || product.GetHashCode() != hc) { return Content("商品信息不存在,或非法進入!1002"); } ViewData["product"] = product; } } //通過,用code換取access_token var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code); if (openIdResult.errcode != ReturnCode.請求成功) { return Content("錯誤:" + openIdResult.errmsg); } string sp_billno = Request["order_no"]; if (string.IsNullOrEmpty(sp_billno)) { //生成訂單10位序列號,此處用時間和隨機數生成,商戶根據自己調整,保證唯一 sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId, DateTime.Now.ToString("yyyyMMdd"), TenPayV3Util.BuildRandomStr(10)); } else { sp_billno = Request["order_no"]; } var timeStamp = TenPayV3Util.GetTimestamp(); var nonceStr = TenPayV3Util.GetNoncestr(); var body = product == null ? "test" : product.Name; var price = product == null ? 100 : product.Price * 100; var xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, sp_billno, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openIdResult.openid, TenPayV3Info.Key, nonceStr); var result = TenPayV3.Unifiedorder(xmlDataInfo);//調用統一訂單接口 //JsSdkUiPackage jsPackage = new JsSdkUiPackage(TenPayV3Info.AppId, timeStamp, nonceStr,); var package = string.Format("prepay_id={0}", result.prepay_id); ViewData["appId"] = TenPayV3Info.AppId; ViewData["timeStamp"] = timeStamp; ViewData["nonceStr"] = nonceStr; ViewData["package"] = package; ViewData["paySign"] = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package, TenPayV3Info.Key); return View(); } catch (Exception ex) { var msg = ex.Message; msg += "<br>" + ex.StackTrace; msg += "<br>==Source==<br>" + ex.Source; if (ex.InnerException != null) { msg += "<br>===InnerException===<br>" + ex.InnerException.Message; } return Content(msg); } }
新聞熱點
疑難解答