入口文件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开发数据传输签名验证。