anyuan2002.com - vwin网

查找: 您的方位主页 > 电脑频道 > 编程代码 > 阅览资讯:微信大众渠道付出开发具体介绍

微信大众渠道付出开发具体介绍

2017-08-07 12:10:00 来历:www.anyuan2002.com 【

微信大众渠道付出开发具体介绍

业务流程

下面是微信的官方流程,看似有点杂乱,要点便是要拿到一致下单接口回来的json串,其他依照官方demo根本就能正确,下面说一下几个细节。

创立订单

在调用微信大众号付出之前,首要咱们自己要把订单创立好。比方一个充值的订单。主要是先确定下金额再进行下一步。

vwin娱乐场
public JsonResult CreateRecharegOrder(decimal money)
 {
 if (money < (decimal)0.01) return Json(new PaymentResult("充值金额不合法!"));
 var user = _workContext.CurrentUser;
 var order = _paymentService.CreateRechargeOrder(user.Id, money);
 return Json(new PaymentResult(true) {OrderId = order.OrderNumber});
 }

调用一致下单

订单创立成功之后,页面跳转到付出页面,这个时分便是依照官方的流程去拿prepay_id和paySign,微信的demo中供给了一个jsApiPay的目标。但这个目标需求一个page目标初始化。

[LoginValid]
 public ActionResult H5Pay(string orderNumber)
 {
 var user = _workContext.CurrentUser;
 var order = _paymentService.GetOrderByOrderNumber(orderNumber);
 //判别订单是否存在
 //订单是否现已付出了
 var openid = user.OpenId;
 var jsApipay = new JsApiPayMvc(this.ControllerContext.HttpContext);
 jsApipay.openid = openid;
 jsApipay.total_fee = (int)order.Amount * 100;
 WxPayData unifiedOrderResult = jsApipay.GetUnifiedOrderResult();
 ViewBag.wxJsApiParam = jsApipay.GetJsApiParameters();//获取H5调起JS API参数 
 ViewBag.unifiedOrder = unifiedOrderResult.ToPrintStr();
 ViewBag.OrderNumber = order.OrderNumber;
 return View();
 }

JsApiPayMvc:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using System.Net;
using System.Web.Security;
using LitJson;
namespace WxPayAPI
{
 public class JsApiPayMvc
 {
 /// <summary>
 /// 保存页面目标,由于要在类的办法中运用Page的Request目标
 /// </summary>
 public HttpContextBase context { get; set; }
 /// <summary>
 /// openid用于调用一致下单接口
 /// </summary>
 public string openid { get; set; }
 /// <summary>
 /// access_token用于获取收货地址js函数进口参数
 /// </summary>
 public string access_token { get; set; }
 /// <summary>
 /// 产品金额,用于一致下单
 /// </summary>
 public int total_fee { get; set; }
 /// <summary>
 /// 一致下单接口回来成果
 /// </summary>
 public WxPayData unifiedOrderResult { get; set; }
 public JsApiPayMvc(HttpContextBase _context)
 {
 context = _context;
 }
 /**
 * 
 * 网页授权获取用户根本信息的悉数进程
 * 概况请参看网页授权获取用户根本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
 * 第一步:运用url跳转获取code
 * 第二步:运用code去获取openid和access_token
 * 
 */
 public void GetOpenidAndAccessToken(string code)
 {
 if (!string.IsNullOrEmpty(code))
 {
 //获取code码,以获取openid和access_token
 Log.Debug(this.GetType().ToString(), "Get code : " + code);
 GetOpenidAndAccessTokenFromCode(code);
 }
 else
 {
 //结构网页授权获取code的URL
 string host = context.Request.Url.Host;
 string path = context.Request.Path;
 string redirect_uri = HttpUtility.UrlEncode("http://" + host + path);
 WxPayData data = new WxPayData();
 data.SetValue("appid", WxPayConfig.APPID);
 data.SetValue("redirect_uri", redirect_uri);
 data.SetValue("response_type", "code");
 data.SetValue("scope", "snsapi_base");
 data.SetValue("state", "STATE" + "#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码 
 context.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", WxPayConfig.APPID);
 data.SetValue("secret", WxPayConfig.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);
 //保存access_token,用于收货地址获取
 JsonData jd = JsonMapper.ToObject(result);
 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 WxPayException(ex.ToString());
 }
 }
 /**
 * 调用一致下单,取得下单成果
 * @return 一致下单成果
 * @失利时抛反常WxPayException
 */
 public WxPayData GetUnifiedOrderResult()
 {
 //一致下单 
 WxPayData data = new WxPayData();
 data.SetValue("body", "test");
 data.SetValue("attach", "test");
 data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
 data.SetValue("total_fee", total_fee);
 data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
 data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
 data.SetValue("goods_tag", "test");
 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 WxPayException("UnifiedOrder response error!");
 }
 unifiedOrderResult = result;
 return result;
 }
 /**
 * 
 * 从一致下单成功回来的数据中获取微信浏览器调起jsapi付出所需的参数,
 * 微信浏览器调起JSAPI时的输入参数格局如下:
 * {
 * "appId" : "wx2421b1c4370ec43b", //大众号称号,由商户传入 
 * "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 string GetJsApiParameters()
 {
 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());
 string parameters = jsApiParam.ToJson();
 Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
 return parameters;
 }
 /**
 * 
 * 获取收货地址js函数进口参数,概况请参阅收货地址同享接口:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_9
 * @return string 同享收货地址js函数需求的参数,json格局能够直接做参数运用
 */
 public string GetEditAddressParameters()
 {
 string parameter = "";
 try
 {
 string host = context.Request.Url.Host;
 string path = context.Request.Path;
 string queryString = context.Request.Url.Query;
 //这个当地要注意,参加签名的是网页授权获取用户信息时微信后台回传的完好url
 string url = "http://" + host + path + queryString;
 //结构需求用SHA1算法加密的数据
 WxPayData signData = new WxPayData();
 signData.SetValue("appid",WxPayConfig.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",WxPayConfig.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 WxPayException(ex.ToString());
 }
 return parameter;
 }
 }
}

这个页面能够在本地调试,能够比较便利的承认参数是否ok。

引发付出

function onBridgeReady(){
 WeixinJSBridge.invoke(
 'getBrandWCPayRequest', {
 "appId" : "wx2421b1c4370ec43b", //大众号称号,由商户传入 
 "timeStamp":" 1395712654", //时刻戳,自1970年以来的秒数 
 "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 
 "package" : "prepay_id=u802345jgfjsdfgsdg888", 
 "signType" : "MD5", //微信签名办法: 
 "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
 },
 function(res){ 
 if(res.err_msg == "get_brand_wcpay_request:ok" ) {} // 运用以上办法判别前端回来,微信团队慎重提示:res.err_msg将在用户付出成功后回来 ok,但并不确保它肯定牢靠。 
 }
 ); 
}

所以在MVC中要这样写:

@{
 ViewBag.Title = "微信付出";
 Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page" id="Wxpayment">
 <div class="content">
 <div>订单概况:@Html.Raw(ViewBag.unifiedOrder)</div>
 <button id="h5pay" onclick="callpay()">付出</button>
 </div>
 <input type="hidden" value="@ViewBag.OrderNumber" id="ordernum"/>
</div>
<script type="text/javascript">
 //调用微信JS api 付出
 function jsApiCall() {
 WeixinJSBridge.invoke(
 'getBrandWCPayRequest',
 @Html.Raw(ViewBag.wxJsApiParam),//josn串
 function (res)
 {
 WeixinJSBridge.log(res.err_msg);
 //alert(res.err_code + res.err_desc + res.err_msg);
 if (res.err_msg == "get_brand_wcpay_request:ok") {
 var num = $("#ordernum").val();
 $.post("/payment/WeiXinPaySuccess", { ordernumber: num }, function(data) {
 if (data.IsSuccess === true) {
 alert("付出成功");
 location.href = document.referrer;
 } else {
 }
 });
 } 
 if (res.err_msg == 'get_brand_wcpay_request:cancel') {
 $('.button').removeAttr('submitting');
 alert('撤销付出');
 } 
 }
 );
 }
 function callpay()
 {
 if (typeof WeixinJSBridge == "undefined")
 {
 alert("WeixinJSBridge =");
 if (document.addEventListener)
 {
 document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
 }
 else if (document.attachEvent)
 {
 document.attachEvent('WeixinJSBridgeReady', jsApiCall);
 document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
 }
 }
 else
 {
 jsApiCall();
 }
 }
</script>

有必要要用Html.Raw,否则json解析不对,无法付出。这个时分点击页面,会呈现微信的加载作用,但别快乐的太早,仍是会犯错,呈现一个“3当时的URL未注册”

以上便是本文的悉数内容,期望本文的内容对咱们的学习或许作业能带来必定的协助,一起也期望多多支撑vwin!


本文地址:http://www.anyuan2002.com/bcdm/90831.html
Tags: 微信 大众 渠道
修改:vwin网
m88 188bet uedbet 威廉希尔 明升 bwin 明升88 bodog bwin 明升m88.com 18luck 188bet unibet unibet Ladbrokes Ladbrokes casino m88明升 明升 明升 m88.com 188bet m88 明陞 uedbet赫塔菲官网 365bet官网 m88 help
188bet www.188bet.com bwin 平博 unibet 明升 188bet uk Ladbrokes 德赢vwin 188bet m88.com w88 平博88 uedbet体育 188bet 188bet 威廉希尔 明升体育app 平博88 M88 Games vwin德赢 uedbet官网 bodog fun88 188bet
推行内容
引荐阅览
抢手引荐
引荐文章
关于咱们 | 联络咱们 | 友情链接 | 网站地图 | Sitemap | App | 回来顶部