C#微信支付分爬坑記之創建微信支付分


時隔多年,又來搞微信支付了。這次是《微信支付分》。

想到多年前的,微信支付,就把人搞的半死不活。官方SDK死活跑不通,微信那幫技術想必都是JAVA抓來的壯丁

想想過了這么久,微信應該對.net該重視了吧。

話不多說,擼起袖子,干!!!

哇塞、官方文檔寫的不錯噢~~

微信支付分文檔地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/pages/payscore.shtml

看了下接入流程,一步步按照操作。

第一步,獲取微信支付分server_id

商戶向wechatpay_scoreBD@tencent.com發送郵件接入申請,微信側在3-5個工作日內進行評估並回復審核結果。申請需包含以下信息:

經過幾天漫長的等待,終於收到郵件了,讓加一個微信號。

提交了一些信息后,終於收到了server_id.

第二步,創建微信支付分訂單

創建微信支付訂單API文檔地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/payscore/chapter3_1.shtml

看了下接口說明

這里有個接口規則,這里要划重點了。

進行不下去了,要仔細研究wechatpay-api-v3接口規則

wechatpay-api-v3接口地址:https://wechatpay-api.gitbook.io/wechatpay-api-v3/

這個文檔看着也簡單,也看的明白。

尼瑪.NET是被微信歧視了么,又沒有.NET的SDK.

反正是習慣了,繼續看下去吧。

看着看着,這里進入了無盡的深淵,只想說太他么難了。

萬萬沒想到,這才是開端。

wechatpay-api-v3簽名生成

微信官方有.NET的代碼示例,我就不貼了。

用了官方的實例,調了很長時間。終於調通了client.GetAsync("https://api.mch.weixin.qq.com/v3/certificates");

client.GetAsync可以用。(這里說明下,System.Net.Http必須要.net framework 4.5以上)

<%@ Page  Async="true" %>

這里必須要加 這個表頭,不然就跑不通的。

client.PostAsync就死活用不了。

可是微信支付分全部都是POST的接口。

實在沒有辦法,搞了好久,全網搜索相關信息,發現有的只是JAVA,PHP的一些零星的片段。

這里貼出我重新自己寫的代碼

 public static string setAuthorization(string method, string noHttps, string data, string timestamp, string nonce_str)
        {
            string signature = Sign($"{method}\n{noHttps}\n{timestamp}\n{nonce_str}\n{data}\n", config.wx_privateKey);
            return $"WECHATPAY2-SHA256-RSA2048 mchid=\"{config.wx_mchid}\",nonce_str=\"{nonce_str}\",timestamp=\"{timestamp}\",serial_no=\"{config.wx_serial_no}\",signature=\"{signature}\"";                    
        }

        public static HttpClient gClient() {
            HttpClient client = new HttpClient();            
            client.DefaultRequestHeaders.Add("Accept", "application/json");         
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");//這里必須要填,不填接口會沒反應。                 
            return client;
        }
        public static string get(HttpClient client,string https)
        {     var cg = client.GetAsync(https);
                cg.Wait();
                cg.Result.EnsureSuccessStatusCode();
                var cgContent = cg.Result.Content.ReadAsStringAsync();
                cgContent.Wait();
                return cgContent.Result;           
        }
     
        public static string post(HttpClient client, string https,string data)
        {
var cp = client.PostAsync(https, new StringContent(data, Encoding.UTF8, "application/json"));
                cp.Wait();
                cp.Result.EnsureSuccessStatusCode();
                var cpContent = cp.Result.Content.ReadAsStringAsync();
                cpContent.Wait();
                return cpContent.Result;            
        }

終於完成了對wechatpay-api-v3的封裝。

可以接着上面第二步,創建微信支付分訂單。

第2.5步,創建微信支付分訂單。

按照要求將上面的請求參數,轉換成json字符串POST提交到https://api.mch.weixin.qq.com/v3/payscore/serviceorder

這里還挺順利的,很快得到了數據反饋。

這里主要要保存這個package信息,下面要用到

H5調起支付分-確認訂單

這里不要問我為什么用H5,我只想說,其他的小程序APP,用的時候都要審核,我嫌麻煩,就是懶。

下面是官方貼出來的代碼。

let wechatInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
let wechatVersion = wechatInfo[1];
​
if (compareVersion(wechatVersion, '7.0.5') >= 0) {
   goToWXScore();
} else {
   // 提示用戶升級微信客戶端版本
   window.href = 'https://support.weixin.qq.com/cgi-bin/readtemplate?t=page/common_page__upgrade&
   text=text005&btn_text=btn_text_0'
}
​
/**
 * 跳轉微信支付分
 */
function goToWXScore() {
    wx.checkJsApi({
        jsApiList: ['openBusinessView'], // 需要檢測的JS接口列表
        success: function (res) {
        // 以鍵值對的形式返回,可用的api值true,不可用為false
        // 如:{"checkResult":{"openBusinessView":true},"errMsg":"checkJsApi:ok"}
        if (res.checkResult.openBusinessView) {
            wx.invoke(
                'openBusinessView', {
                    businessType: 'wxpayScoreUse',
                    queryString
: 'mch_id=1230000109&package=xxxxx&
			timestamp=1530097563&nonce_str=zyx53Nkey8o4bHpxTQvd8m7e92nG5mG2&sign_type=HMAC-SHA256&
			sign=029B52F67573D7E3BE74904BF9AEA'
                },
                function (res) {
                // 從支付分返回時會執行這個回調函數
                    if (parseInt(res.err_code) === 0) {
                    // 返回成功 
                    } else {
                    // 返回失敗
                    }
                });
            }
        }
    });
 }
​
 /**
  * 版本號比較
  * @param {string
} v1 
  * @param {string
} v2 
  */
function compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
  
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
  
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
  
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
  
    return 0
 }

  其中重要的信息是:queryString,sign

這里需要按照簽名生成法計算出簽名值。

簽名算法

這個是官方給出的算法說明。

我貼一下.NET的相應的算法代碼

 public static string SHA256(string plaintext,string APIKey)
        {
            string result = "";
            var enc = Encoding.Default;
            byte[]
            baText2BeHashed = enc.GetBytes(plaintext),
            baSalt = enc.GetBytes(APIKey);
            HMACSHA256 hasher = new HMACSHA256(baSalt);
            byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
            result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
            return result.ToUpper();
        }

終於算出queryString。

填入,開始運行沒有成功。

原來要先微信先wx.config驗證

 wx.config({
        debug: false, appId: '<%=appId%>', timestamp: <%=timestamp%>, nonceStr: '<%=nonceStr%>', signature: '<%=signature%>', jsApiList: ['openBusinessView']
    });    
    var pay = function () {
        wx.ready(function () {
            wx.invoke('openBusinessView', { businessType: 'wxpayScoreUse', queryString: '<%=queryString%>' }, function (res) {                
              
            });
        });
    };    

這樣就成功了。

附上兩張實用圖。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM