入口文件index.php代碼
1 <?php
2 include './Base.php';
3
4 class WeiXinPay extends Base
5 {
6 public function __construct()
7 {
8 $arr = [
9 'appid' =>'dkdfg',
10 'mch_id'=>'sdfgd',
11 'body'=>'2347京東商城',
12 // 'sing'=>'CBEF716EF1A065E6979DE3170BE3B6B8',
13 ];
14 //要驗證的簽名數組
15 $arr = $this->setSing($arr);
16 // print_r($arr);
17 //更改KEY 簽名驗證失敗
18 // $arr['sing'] = '1';
19 if($this->checkSing($arr))
20 {
21 echo '驗證簽名成功';
22 }
23 else
24 {
25 echo '驗證簽名失敗';
26 }
27 }
28 }
29
30 $obi = new WeiXinPay();
Base.php 文件代碼
1 <?php
2 header("Content-type: text/html; charset=utf-8");
3 /**
4 * Created by PhpStorm.
5 * User: lsh
6 * Date: 2099/3/25
7 * Time: 16:08
8 */
9
10 class Base
11 {
12 //商戶id
13 const KEY ='kkkkksdio87923';
14
15 //生成簽名
16 public function getSign($arr)
17 {
18 //去除數組中的空值
19 $arr = array_filter($arr);
20 //如果數組中有簽名刪除簽名
21 if(isset($arr['sing']))
22 {
23 unset($arr['sing']);
24 }
25 //按照鍵名字典排序
26 ksort($arr);
27 //生成URL格式的字符串
28 //http_build_query()中文自動轉碼需要處理下
29 $str = http_build_query($arr)."&key=".self::KEY;
30 //echo $str;
31 //appid=dkdfg&body=2347%E4%BA%AC%E4%B8%9C%E5%95%86%E5%9F%8E&mch_id=sdfgd&key=kkkkksdio87923CBEF716EF1A065E6979DE3170BE3B6B8
32 $str = $this->arrToUrl($str);
33 //echo $str;
34 //header("Content-type: text/html; charset=utf-8");
35 // echo strtoupper(md5($str));
36 return strtoupper(md5($str));
37 }
38
39 //獲取簽名 待簽名的數組
40 public function setSing($arr)
41 {
42 $arr['sing'] = $this->getSign($arr);
43 return $arr;
44 }
45
46 //URL解碼爲中文
47 public function arrToUrl($str)
48 {
49 return urldecode($str);
50 }
51 //驗證簽名
52 public function checkSing($arr)
53 {
54 //獲取簽名
55 $sing = $this->getSign($arr);
56 if($sing == $arr['sing'])
57 {
58 return true;
59 }
60 else
61 {
62 return false;
63 }
64 }
65 }
同樣適用於APP開發數據傳輸簽名驗證。
2020 PHP簽名驗證算法,微信支付簽名
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.