月度归档: 2019 年 12 月

  • php 一个文件搞定  提交付款码支付 应用场景

    php 一个文件搞定 提交付款码支付 应用场景

    应用场景

    收银员使用扫码设备读取微信用户付款码以后,二维码或条码信息会传送至商户收银台,由商户收银台或者商户后台调用该接口发起支付。

    提醒1:提交支付请求后微信会同步返回支付结果。当返回结果为“系统错误”时,商户系统等待5秒后调用【查询订单API】,查询支付实际交易结果;当返回结果为“USERPAYING”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒);

    提醒2:在调用查询接口返回后,如果交易状况不明晰,请调用【撤销订单API】,此时如果交易失败则关闭订单,该单不能再支付成功;如果交易成功,则将扣款退回到用户账户。当撤销无返回或错误时,请再次调用。注意:请勿调用扣款后立即调用【撤销订单API】,建议至少15s后再调用。撤销订单API需要双向证书。

    官方文档地址:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_10&index=1

    具体代码

    建立文件pay.php

    <?php
    $key = "0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";						//微信商户API密钥
    $arr['auth_code'] = $_GET['auth_code'];
    $arr['appid']  = "xxxxxxxxxxxxxxxxxx";								//应用APPID
    $arr['mch_id'] = "1311111111";												//微信支付商户号
    $arr['sub_mch_id'] = '1561111111';										//子商户号
    $arr['out_trade_no'] = date('YmdHis').rand(1000,9999);//平台内部订单号
    $arr['body'] = "扫码支付";														//内容
    $arr['total_fee'] = 1; 																//金额
    $arr['nonce_str'] = md5(rand(1000, 999999));					//随机字符串
    $arr['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];   //获得用户设备IP 
    ksort($arr);
    $sign_tmp = $xml_tmp = '';
    foreach($arr as $k => $v){
    	$sign_tmp .= "$k=$v&";
    	$xml_tmp .= "<$k>$v</$k>";
    }
    $sign = strtoupper(MD5($sign_tmp . "key=$key")); 				//MD5后转换成大写
    $xml = "<xml>$xml_tmp<sign>$sign</sign></xml>";
    $url = "https://api.mch.weixin.qq.com/pay/micropay";		//微信传参地址
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);									//设置超时
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);								//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 				//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, TRUE);										//POST提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    $dataxml = curl_exec($ch);															//运行curl
    if(!$dataxml){
        $error = curl_errno($ch);
        echo "curl出错,错误码:$error"."<br>";
    }
    curl_close($ch);
    //将微信返回的XML 转换成数组
    $rs = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); 
    echo 'over';
    print_r($rs);

    拼接后的XML举例如下:

    <xml>
       <appid>wx2421b1c4370ec43b</appid>
       <attach>订单额外描述</attach>
       <auth_code>120269300684844649</auth_code>
       <body>付款码支付测试</body>
       <device_info>1000</device_info>
       <goods_tag></goods_tag>
       <mch_id>10000100</mch_id>
    <sub_mch_id>10000101</sub_mch_id>
       <nonce_str>8aaee146b1dee7cec9100add9b96cbe2</nonce_str>
       <out_trade_no>1415757673</out_trade_no>
       <spbill_create_ip>14.17.22.52</spbill_create_ip>
       <time_expire></time_expire>
       <total_fee>1</total_fee>
       <sign>C29DB7DB1FD4136B84AE35604756362C</sign>
    </xml>

    注:参数值用XML转义即可,CDATA标签用于说明数据不被XML解析器解析。

    使用方法

    pay.php?auth_code=135610584558

    将下图中的二维码数字输入auth_code值中即可。

  • Python django migrate 和makemigrations的实际应用举例

    Python django migrate 和makemigrations的实际应用举例

    测试环境中生成迁移

    在你改动了 model.py的内容之后执行下面的命令:

    python manager.py makemigrations

    相当于 在该app下建立 migrations目录,并记录下你所有的关于modes.py的改动,比如0001_initial.py,

     但是这个改动还没有作用到数据库文件

    你可以手动打开这个文件,看看里面是什么

    生产环境中生成执行迁移

    python manager.py migrate

    将该改动作用到数据库文件,比如产生table之类

  • Python机房流量调度系统 环境配置

    Python机房流量调度系统 环境配置

    前面我们写了Python3 机房间流量调度系统,下面我们记录一下安装环境配置。

    升级Linux系统下的Python版本

    CentOS上安装配置Python3.7 编译安装图文教程

    安装docker

    yum install docker git screen -y
    systemctl start docker.service
    mkdir -p /data/mysqlData

    配置docker mysql

    docker run -d -p 3307:3306 -v /data/mysqlData/:/var/lib/mysql --privileged=true --name jmysql -e MYSQL_ROOT_PASSWORD='laoji.org' mysql 

    进入mysql容器,配置mysql密码

    docker exec -it jmysql /bin/bash
    mysql -uroot -p
    use mysql;
    alter user 'root'@'%' identified with mysql_native_password by 'laoji.org';
    \q
    exit 

    后面导入数据等不再详细说明。

  • Linux限制IP登录ssh

    前面我们介绍了Linux相关的安全知识:

    如何限制Linux系统ip登录访问?

    vi /etc/hosts.allow
    ALL:180.97.171.xxx
    sshd:ALL:deny

    这样的话即使/etc/hosts.deny不填任何内容,也只允许固定的IP访问。

    /etc/hosts.allow控制可以访问本机的IP地址,/etc/hosts.deny控制禁止访问本机的IP。如果两个文件的配置有冲突,以/etc/hosts.deny为准。

    /etc/hosts.allow和/etc/hosts.deny两个文件是控制远程访问设置的,通过他可以允许或者拒绝某个ip或者ip段的客户访问linux的某项服务。

  • Django数据库分表代码实例

    Django数据库分表代码实例

    app名称为‘core’,基本的models.py文件内容如下:

    class Province(models.Model):
        name = models.CharField(u'省份名称',max_length=32)
        code = models.IntegerField(verbose_name=u'区号', unique=True)
        
        def __unicode__(self):
            return self.name
        
        class Meta:
            verbose_name = u'省份列表'
            verbose_name_plural = u'省份列表'

    法I:

    重构 manager 中的 get_query_set() 方法。

    需要说明的是:在 django 默认情况下,会为每一个models 类添加一个名为 objects 的 Manager,这个就是 Province.objects.all() 中 objects 的由来。

    修改后的 models.py 代码如下,表结构必须一致:

    # coding:utf-8
    from django.db import models
    # Create your models here.
    class ProvinceManager(models.Manager):
        def get_queryset(self):
    #         return super(ProvinceManager, self).get_queryset().filter(id=1)
            self.model._meta.db_table = 'core_province_1' # 我的app名为core
            return super(ProvinceManager, self).get_queryset()10         11     
    class Province(models.Model):
        name = models.CharField(u'省份名称',max_length=32)
        code = models.IntegerField(verbose_name=u'区号', unique=True)
        
        objects = ProvinceManager()
        
        def __unicode__(self):
            return self.name
        
        class Meta:
            verbose_name = u'省份列表'
            verbose_name_plural = u'省份列表'

    可以多写几个 Manager 来对应不同的表,同时对应多写几个不同的 objects(可以随意起名),在调用时调用相应的 Manager。

    法II:

    在哪里调用就在哪里更改。更改处添加代码如下:

    from core.models import Province
    Province._meta.db_table = 'core_prvoince_2'
    rows = Province.objects.all() 

    总结:

    不论哪种方法,其主要还是要更改 models 的 _meta.db_table 的值

  • Python3 生成随机密码 代码实例

    Python3 生成随机密码 代码实例

    Python3 生成随机密码 代码实例

    def generate_password():
        import random
        length = 64
        seed = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        print(''.join(random.choice(seed) for _ in range(length)))
    
  • jQuery插件 — Cookie插件jquery.cookie.js 使用实例

    jQuery插件 — Cookie插件jquery.cookie.js 使用实例

    Cookie是网站设计者放置在客户端的小文本文件。Cookie能为用户提供很多的使得,例如购物网站存储用户曾经浏览过的产品列表,或者门户网站记住用户喜欢选择浏览哪类新闻。 在用户允许的情况下,还可以存储用户的登录信息,使得用户在访问网站时不必每次都键入这些信息

    使用方法:

    引入jquery.cookie.js

    <script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>  
    <script src="scripts/jquery.cookie.js" type="text/javascript"></script>

    使用方法

    新添加一个会话 cookie

    $.cookie('the_cookie', 'the_value');

    注:当没有指明 cookie有效时间时,所创建的cookie有效期默认到用户关闭浏览器为止,所以被称为

    “会话cookie(session cookie)”。

    创建一个cookie并设置有效时间为 7天:

    $.cookie('the_cookie', 'the_value', { expires: 7 });

    注:当指明了cookie有效时间时,所创建的cookie被称为“持久 cookie (persistent  cookie)”。 

    创建一个cookie并设置 cookie的有效路径:

    $.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

    注:在默认情况下,只有设置 cookie的网页才能读取该 cookie。如果想让一个页面读取另一个页面设置的cookie,必须设置cookie的路径。cookie的路径用于设置能够读取 cookie的顶级目录。将这个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突) 。 

    读取cookie:

    $.cookie('the_cookie'); // cookie存在 => 'the_value'
    $.cookie('not_existing'); // cookie不存在 => null

    删除cookie,通过传递null作为cookie的值即可:

    $.cookie('the_cookie', null);

    将cookie写入文件

    var COOKIE_NAME = 'username';  
        if( $.cookie(COOKIE_NAME) ){  
            $("#username").val(  $.cookie(COOKIE_NAME) );  
        }  
        $("#check").click(function(){  
            if(this.checked){  
                $.cookie(COOKIE_NAME, $("#username").val() , { path: '/', expires: 10, domain: 'jquery.com', secure: true });  
                //var date = new Date();  
                //date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期  
                //$.cookie(COOKIE_NAME, $("#username").val(), { path: '/', expires: date });  
            }else{  
                $.cookie(COOKIE_NAME, null, { path: '/' });  //删除cookie  
            }  
        });

    参数设置

    expires: (Number | Date)      有效期,可以设置一个整数作为有效期(单位:天),也可以设置一个日期对象作为Cookie的过期日期。如果指定日期为负数,那么此cookie将被删除;如果不设置或者设置为null,那么此cookie将被当作Session Cookie处理,并且在浏览器关闭后删除

    path:  (String)          Cookie的路径属性,默认是创建该cookie的页面路径

    domain: (String)     Cookie的域名属性,默认是创建该cookie的页面域名

    secure: (Boolean)  如果设为true,那么此cookie的传输会要求一个安全协议,例如HTTPS

    jquery.cookie.js

    /**
     * Cookie plugin
     *
     * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
     * Dual licensed under the MIT and GPL licenses:
     * http://www.opensource.org/licenses/mit-license.php
     * http://www.gnu.org/licenses/gpl.html
     *
     */
    /**
     * Create a cookie with the given name and value and other optional parameters.
     *
     * @example $.cookie('the_cookie', 'the_value');
     * @desc Set the value of a cookie.
     * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
     * @desc Create a cookie with all available options.
     * @example $.cookie('the_cookie', 'the_value');
     * @desc Create a session cookie.
     * @example $.cookie('the_cookie', null);
     * @desc Delete a cookie by passing null as value.
     *
     * @param String name The name of the cookie.
     * @param String value The value of the cookie.
     * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
     * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
     *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
     *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
     *                             when the the browser exits.
     * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
     * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
     * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
     *                        require a secure protocol (like HTTPS).
     * @type undefined
     *
     * @name $.cookie
     * @cat Plugins/Cookie
     * @author Klaus Hartl/klaus.hartl@stilbuero.de
     */
    /**
     * Get the value of a cookie with the given name.
     *
     * @example $.cookie('the_cookie');
     * @desc Get the value of a cookie.
     *
     * @param String name The name of the cookie.
     * @return The value of the cookie.
     * @type String
     *
     * @name $.cookie
     * @cat Plugins/Cookie
     * @author Klaus Hartl/klaus.hartl@stilbuero.de
     */
    jQuery.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
  • ‘WSGIRequest’ object has no attribute ‘Get’解决办法

    ‘WSGIRequest’ object has no attribute ‘Get’解决办法

    出现问题

    ‘WSGIRequest’ object has no attribute ‘Get’

    解决办法

    这个原因是request只有GET和POST方法,注意都是大写,如果你也遇到这个问题,可以全局查找一下,哪里写成小写了,很简单,问题就解决了

    request.GET.get('a')
    request.POST.get('b')

  • 2019腾讯云 双12 秒杀活动 1核2G1M国内服务器仅需¥99元/年

    2019腾讯云 双12 秒杀活动 1核2G1M国内服务器仅需¥99元/年

    已经进入十二月份,还有一个月将跨入新的2020年。各大云服务商结束双十一和黑五促销活动之后,再次迎来双十二活动,尤其是以腾讯云、阿里云为首的国内云商家,这样连续的大促活动确实给其他商家不小的打击无还手之力。今天老季和大家一起看看新的2019年腾讯云双12活动形式以及有哪些值得购买的云产品。

    活动地址:腾讯云 双12 限时秒杀 云服务器 1核2G ¥99元/年

    第一、每天限时秒杀活动

    从活动方案看,腾讯云俗称良心云,直接很简单的秒杀限时活动。双12活动中,每天有四场活动。分别是9:00、13:00、16:00、19:00四个时间段。

    我们可以看到最低年付2G1M上海服务器年99元,中国香港1G1M年付249元一年,其他还有两年三年套餐,但是相对双十一活动是贵一点的。但是比平时常规价格是便宜。

    第二、新企业云服务器优惠

    如果我们是企业或者是有企业资质的,购买腾讯云企业专享的云产品是比个人丰富且便宜的。比如这次双12活动中,企业新用户可以购买到5-10M带宽的云服务器,适合企业应用场景。

    这里我们可以看看到2核4G内存5M带宽三年仅需要1200元,其他更有最大10M带宽的服务器可以选择。

    除了上面两个仅限新注册个人或者企业用户之外,其他双十二腾讯云活动云服务器及其他云产品有低至三折起步,不限制是新人购买,如果有需要的也可以看看。

WeChat