微信小程序支付 记录

private $appid  = "" ;
private $secret = "";
private $mch_id = '';
private $key = '';
private $openid = '';
public function index(){
    $this->load->library('wxpay');

    $code = $this->input->post("code");
    $total_fee = $this->input->post("total_fee");
    $total_fee = $total_fee?:1;

    //获取openid
    if($code)
    {
        $WX_APPID = $this->appid;
        $WX_SECRET = $this->secret;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code";
        $infos = json_decode(file_get_contents($url));
        $openid = $infos->openid;
    }
    if(!$openid){
        $openid = $this->openid();
    }

    $appid =        $this->appid;//如果是公众号 就是公众号的appid
    $body =         '小程序支付';
    $mch_id =       $this->mch_id;
    $nonce_str =    $this->nonce_str();//随机字符串
    $notify_url =   'test';
    $openid =      $openid;
    $out_trade_no = time();//商户订单号
    $spbill_create_ip = '127.0.0.1';
    $total_fee =    $total_fee;//因为充值金额最小是1 而且单位为分 如果是充值1元所以这里需要*100
    $trade_type = 'JSAPI';//交易类型 默认


    //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
    $post['appid'] = $appid;
    $post['body'] = $body;
    $post['mch_id'] = $mch_id;
    $post['nonce_str'] = $nonce_str;//随机字符串
    $post['notify_url'] = $notify_url;
    $post['openid'] = $openid;
    $post['out_trade_no'] = $out_trade_no;
    $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
    $post['total_fee'] = $total_fee;//总金额 最低为一块钱 必须是整数
    $post['trade_type'] = $trade_type;
    $sign = $this->sign($post);//签名
    
    $post_xml = '<xml>
           <appid>'.$appid.'</appid>
           <body>'.$body.'</body>
           <mch_id>'.$mch_id.'</mch_id>
           <nonce_str>'.$nonce_str.'</nonce_str>
           <notify_url>'.$notify_url.'</notify_url>
           <openid>'.$openid.'</openid>
           <out_trade_no>'.$out_trade_no.'</out_trade_no>
           <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
           <total_fee>'.$total_fee.'</total_fee>
           <trade_type>'.$trade_type.'</trade_type>
           <sign>'.$sign.'</sign>
        </xml> ';
    //统一接口prepay_id
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $xml = $this->http_request($url,$post_xml);

    $array = $this->xml($xml);//全要大写
    if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){
        $time = time();
        $tmp='';//临时数组用于签名
        $tmp['appId'] = $appid;
        $tmp['nonceStr'] = $nonce_str;
        $tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
        $tmp['signType'] = 'MD5';
        $tmp['timeStamp'] = "$time";
        $data['state'] = 1;
        $data['timeStamp'] = "$time";//时间戳
        $data['nonceStr'] = $nonce_str;//随机字符串
        $data['signType'] = 'MD5';//签名算法,暂支持 MD5
        $data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
        $data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
        $data['out_trade_no'] = $out_trade_no;


    }else{
        $data['state'] = 0;
        $data['text'] = "错误";
        $data['RETURN_CODE'] = $array['RETURN_CODE'];
        $data['RETURN_MSG'] = $array['RETURN_MSG'];
    }
    echo json_encode($data); //小程序需要的数据 返回前端

}

public function sign($data){
    $stringA = '';
    foreach ($data as $key=>$value){
        if(!$value) continue;
        if($stringA) $stringA .= '&'.$key."=".$value;
        else $stringA = $key."=".$value;
    }
    $wx_key = $this->key;//申请支付后有给予一个商户账号和密码,登陆后自己设置key
    $stringSignTemp = $stringA.'&key='.$wx_key;//申请支付后有给予一个商户账号和密码,登陆后自己设置key
    return strtoupper(md5($stringSignTemp));
}

public function nonce_str(){
    $result = '';
    $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
    for ($i=0;$i<32;$i++){
        $result .= $str[rand(0,48)];
    }
    return $result;
}

function http_request($url,$data = null,$headers=array())
{
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);


    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

private function xml($xml){
    $p = xml_parser_create();
    xml_parse_into_struct($p, $xml, $vals, $index);
    xml_parser_free($p);
    $data = "";
    foreach ($index as $key=>$value) {
        if($key == 'xml' || $key == 'XML') continue;
        $tag = $vals[$value[0]]['tag'];
        $value = $vals[$value[0]]['value'];
        $data[$tag] = $value;
    }
    return $data;
}
payStart:function(){
    var total_fee = total_fee; 
    wx.login({
      success: res => {  
         //code 用于获取openID的条件之一
        var code = res.code;
        wx.request({
          url: 'http://xxx/xx/x',
          method: "POST",
          data: {
            total_fee:2,
            code: code,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: function (res) {  //后端返回的数据
            var data = res.data;
            console.log(data);
            console.log(data["timeStamp"]);
            wx.requestPayment({
              timeStamp: data['timeStamp'],
              nonceStr: data['nonceStr'],
              package: data['package'],
              signType: data['signType'],
              paySign: data['paySign'],
              success: function (res) {
                wx.showModal({
                  title: '支付成功',
                  content: '',
                })
              },
              fail: function (res) {
                console.log(res);
              }
            })
          }
        }); 
      }
    })
  }

 

微信支付 fopen(/tmp/logs/.log): failed to open stream: No such file or directory 与 curl出错,错误码:60 解决方法

调试微信支付发生错误

错误1:

A PHP Error was encountered
Severity: Warning
Message: fopen(/tmp/logs/2018-05-30.log): failed to open stream: No such file or directory
Filename: lib/log.php
Line Number: 16

解决方法:在硬盘的根目录下新建 tmp/logs/ 文件夹,不是在网站根目录下新建文件夹

错误2:

An uncaught Exception was encountered
Type: WxPayException
Message: curl出错,错误码:60
Filename: D:\wwwroot\wanaiweb\wanai\application\third_party\wxpay\lib\WxPay.Api.php
Line Number: 564

修改文件 WxPay.Api.php 解决:

第537行

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验

改为

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验2

 

CI CodeIgniter 添加打印 dump 公共函数(自定义函数)

CodeIgniter 公共函数通过 helper 辅助函数实现。

创建 common_helper.php 文件,定义所需公共函数,存放至 application/helpers 目录中。

<?php
  function dump($arr){
    echo "<pre>";
    var_dump($arr);
    echo "</pre>";
  }
  function dd($arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
  }
?>

在 application/config/autoload.php 中配置 $autoload[‘helper’] = array(‘common’);

PHP GET 调用企查查 API 示例

/* PHP CURL HTTPS GET*/
function curl_get_https($url){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象
}
public function test(){
    $url = 'http://i.yjapi.com/ECIV4/Search?';
    $key = '';
    $keyword = '小桔科技';
    $get = http_build_query(array('key'=>$key,'keyword'=>$keyword));
    $rs = $this->curl_get_https($url.$get);
    echo $rs;
}

返回值:

{
"Status": "202",
"Message": "传入参数有误,请检查",
"OrderNumber": null,
"Paging": null,
"Result": null
}

 

请实现一个显示层级目录的函数 – 一道 PHP 面试题

题有问题暂且不说,说一下解题思路,未总结成方法

<?php
$dir = [
    '0'=>['','主目录'],
    '1'=>['0','第一级目录1'],
    '2'=>['0','第一级目录2'],
    '3'=>['0','第一级目录3'],
    '4'=>['','主目录2'],
    '5'=>['1','第二级目录1'],
    ];
  
foreach($dir as $k => &$v){
    $v['id']= $k;
    $v['pid'] = $v[0];
    $v['title'] = $v[1];
    unset($dir[$k][0],$dir[$k][1]);
}

echo '<pre>';
print_r($dir);
echo '</pre>';

#递归方法实现无限极分类
function getTree($list,$pid=0,$level=0) {
  static $tree = array();
  foreach($list as $row) {
      if($row['pid'] !== ''){
    		if($row['pid']==$pid) {
        		$row['level'] = $level;
        		$tree[] = $row;
        		getTree($list, $row['id'], $level + 1);
        	}
      }elseif($row['pid'] === '' && $level == 0){
          $tree[] = $row;
      }
  }
  return $tree;
}

$dir = getTree($dir);

echo '<pre>';
print_r($dir);
echo '</pre>';

foreach($dir as $kk => $vv){
    if($vv['level'] !== NULL){
        $rs[] = str_repeat('--',$vv['level']+1).$vv['title'];
    }else{
        $rs[] = $vv['title'];
    }
}

echo '<pre>';
print_r($rs);
echo '</pre>';

结果是:

Array
(
    [0] => Array
        (
            [id] => 0
            [pid] => 
            [title] => 主目录
        )

    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => 第一级目录1
        )

    [2] => Array
        (
            [id] => 2
            [pid] => 0
            [title] => 第一级目录2
        )

    [3] => Array
        (
            [id] => 3
            [pid] => 0
            [title] => 第一级目录3
        )

    [4] => Array
        (
            [id] => 4
            [pid] => 
            [title] => 主目录2
        )

    [5] => Array
        (
            [id] => 5
            [pid] => 1
            [title] => 第二级目录1
        )

)
Array
(
    [0] => Array
        (
            [id] => 0
            [pid] => 
            [title] => 主目录
        )

    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => 第一级目录1
            [level] => 0
        )

    [2] => Array
        (
            [id] => 5
            [pid] => 1
            [title] => 第二级目录1
            [level] => 1
        )

    [3] => Array
        (
            [id] => 2
            [pid] => 0
            [title] => 第一级目录2
            [level] => 0
        )

    [4] => Array
        (
            [id] => 3
            [pid] => 0
            [title] => 第一级目录3
            [level] => 0
        )

    [5] => Array
        (
            [id] => 4
            [pid] => 
            [title] => 主目录2
        )

)
Array
(
    [0] => 主目录
    [1] => --第一级目录1
    [2] => ----第二级目录1
    [3] => --第一级目录2
    [4] => --第一级目录3
    [5] => 主目录2

难点在于相较于一般的无限级分类,多了一级 pid == ‘’ ,这一级单独判断。

PHP 编译安装 phpredis

cd ~/Downloads
git clone https://github.com/phpredis/phpredis.git
cd phpredis
/home/misswell/soft/php/bin/phpize
./configure --with-php-config=/home/misswell/soft/php/bin/php-config
make -j
make install

在 php.ini 里添加扩展

vim /home/misswell/soft/php/lib/php.ini

extension=redis