1. 程式人生 > >C# MVC 微信支付教程系列之公眾號支付程式碼

C# MVC 微信支付教程系列之公眾號支付程式碼

今天,我們接著講微信支付的系列教程,前面,我們講了這個微信紅包和掃碼支付。現在,我們講講這個公眾號支付。公眾號支付的應用環境常見的使用者通過公眾號,然後再通過公眾號裡面的菜單鏈接,進入公眾號的商城,然後在裡面完成購買和支付功能,我們可以看看官方對這個公眾號支付的場景的解釋,連結:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1,通過這個官方的解釋,那我們大概清楚這個公眾號的用途了,下面,我就說說,做這個公眾號支付的準備工作有哪些了。

  2、配置“微信支付”環境,如下圖:

3、授權獲取使用者資訊,如下圖:

 下面開始,一步一步往下走。

 

然後右鍵專案,我們修改一下屬性,如下圖:

 

然後我們再把程式自動生成的HomeController.cs和View裡面的刪掉,再新建一個HomeController.cs和新增View,程式碼如下:

?
1234567891011121314151617using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Web.Controllers{public class HomeController : Controller{// GET: Homepublic ActionResult Index()
{return View();}}}

View程式碼:

?
12345678910111213141516@{Layout = null;}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Index</title></head><body><div> </div></body></html>

嗯,沒錯,目前還是空的,現在我們開始寫前臺,程式碼如下(我先貼上程式碼,後續再解釋為啥這麼做,因為如果一步步的寫下去,按照前面兩個的篇幅來,我覺得都可以開課了,所以,我先上程式碼,然後再一步步解釋。):

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243@{Layout = null;}<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>電錶充值服務</title><link href="~/Scripts/jquery-easyui-1.4.5/themes/bootstrap/easyui.css" rel="stylesheet" /><link href="~/Scripts/jquery-easyui-1.4.5/themes/mobile.css" rel="stylesheet" /><link href="~/Scripts/jquery-easyui-1.4.5/themes/icon.css" rel="stylesheet" /><style type="text/css">body{margin:0;padding:0;}.logo {width: 100%;height: 70px;background: url(/Images/EleLogo.png) 0 0 no-repeat;background-size: 100% 100%;padding: 0;margin: 0;}.line {width: 100%;float: left;height: auto;text-align: center;margin-top: 10px;}.lineText {width: 100%;float: left;height: auto;text-indent: 5%;text-align: left;font-size: x-large;margin: 0;}.function {height: 60pt;line-height: 60pt;width: 45%;float: left;border-radius: 10px;background-color: #990000;margin-left: 8pt;}.title {font-family: "微軟雅黑";font-size: x-large;color: white;}a {text-decoration: none;color: white;}input {vertical-align: central;}label {vertical-align: central;}.lbBlock {border: 1px solid #808080;background-color: grey;width: 90%;margin-left: 5%;font-size: x-large;border-radius: 10px;text-align: left;text-indent: 10pt;height: 30pt;padding-top: 5pt;}.btn {width: 90%;height: 35pt;font-size: x-large;background-color: #990000;color: white;background: url(/Images/red.png) 0 0 repeat;border: none;border-radius: 10px;margin: 10px 0 0 0;}.input {height: 30pt;width: 90%;font-size: x-large;border-radius: 10px;margin: 0;padding: 0;}</style></head><body><div class="logo"></div><form id="ChargeForm"<div class="line"><div class="lineText">充值金額:</div></div><div class="line"><input type="number" id="ChargeVal" name="ChargeVal" class="input" placeholder="單位:元" /></div>  </form><div class="line"><input type="button" class="btn" value="立即充值" onclick="fCharge()" style="margin-top: 20px;" /></div><div class="line"><input type="button" id="btnHome" class="btn" value="返回主頁" onclick="fBackHome()" /></div><script src="~/Scripts/jquery-easyui-1.4.5/jquery.min.js"></script><script src="~/Scripts/jquery-easyui-1.4.5/jquery.easyui.min.js"></script><script src="~/Scripts/jquery-easyui-1.4.5/jquery.easyui.mobile.js"></script><script src="~/Scripts/jquery-easyui-1.4.5/easyloader.js"></script><script type="text/javascript">$(function () {var vCode = getQueryString("code");if (vCode != "" && vCode != null) {//alert(vCode);$.ajax({type: 'post',data: {code: vCode},url: '/Home/getWxInfo',success: function (sjson) {//alert(sjson);//var vData = JSON.stringify(sjson);//alert(vData);$.messager.show({title: '提示',msg: '歡迎您來到微信端充值中心。'});}})}else {$.ajax({type: 'post',url: '/Home/getCode',success: function (sjson) {//alert(sjson);location.href = sjson;}})}})//獲取url的引數function getQueryString(name) {var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");var r = window.location.search.substr(1).match(reg);if (r != null) return unescape(r[2]); return null;}//初始化微信支付環境function fCharge() {if (typeof WeixinJSBridge == "undefined") {if (document.addEventListener) {document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);} else if (document.attachEvent) {document.attachEvent('WeixinJSBridgeReady', onBridgeReady);document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);}} else {fPostCharge();}}//提交充值資料function fPostCharge() {var vChargeVal = $("#ChargeVal").val();vChargeVal = parseFloat(vChargeVal);if (vChargeVal > 0) {$.messager.progress({title: "",msg: "正在呼叫微信支付介面,請稍後..."});$.ajax({type: "post",data: "totalfee=" + vChargeVal,url: "/Home/MeterRecharge",success: function (json) {$.messager.progress('close');//記得關閉//var json = eval("(" + msg + ")");//轉換後的JSON物件onBridgeReady(json);},error: function () {$.messager.progress('close');//記得關閉$.messager.alert("提示", '呼叫微信支付模組失敗,請稍後再試。', 'info')}})}else {alert("房間名或者充值金額不可以為空或者為負數,請確認後再試.")}}//呼叫微信支付模組function onBridgeReady(json) {WeixinJSBridge.invoke('getBrandWCPayRequest', {"appId": json.appId,  //公眾號名稱,由商戶傳入"timeStamp": json.timeStamp,   //時間戳,自1970年以來的秒數"nonceStr": json.nonceStr, //隨機串"package": json.packageValue,"signType": "MD5",   //微信簽名方式:"paySign": json.paySign //微信簽名},function (res) {if (res.err_msg == "get_brand_wcpay_request:ok") {//alert("支付成功,請稍後查詢餘額,如有疑問,請聯絡管理員.");fAlreadyPay();// 使用以上方式判斷前端返回,微信團隊鄭重提示:res.err_msg將在使用者支付成功後返回 ok,但並不保證它絕對可靠。});}function fBackHome() {location.href = "/";}</script></body></html>

後臺程式碼如下:

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Web.Models;using WxPayAPI;namespace Web.Controllers{public class HomeController : Controller{JsApiPay jsApiPay = new JsApiPay();// GET: Homepublic ActionResult Index(){if (Session["openid"] == null){try{//呼叫【網頁授權獲取使用者資訊】介面獲取使用者的openid和access_tokenGetOpenidAndAccessToken();}catch (Exception ex){//Response.Write(ex.ToString());//throw;}}return View();}/*** * 網頁授權獲取使用者基本資訊的全部過程* 第一步:利用url跳轉獲取code* 第二步:利用code去獲取openid和access_token* */public void GetOpenidAndAccessToken(){if (Session["code"] != null){//獲取code碼,以獲取openid和access_tokenstring code = Session["code"].ToString();Log.Debug(this.GetType().ToString(), "Get code : " + code);jsApiPay.GetOpenidAndAccessTokenFromCode(code);}else{//構造網頁授權獲取code的URLstring host = Request.Url.Host;string path = Request.Path;string redirect_uri = HttpUtility.UrlEncode( + host + path);//string redirect_uri = HttpUtility.UrlEncode("http://gzh.lmx.ren