初识python wxpy模块之swxpay[简易版微信支付]

测试花了不少时间,只要是我想在服务器上跑这个wxpy项目,所以需要在我的服务器上搭python环境,折腾了不少时间,乱码这种问题等,然后又在tomcat上部署一个small【simple mall】项目(目标是做成类似自动发卡系统,现在还在筹划中…页面怎么写【捂脸】有点愁啊)。目前这个small只是完成了支付模块,尚未成型…

先看效果swxpay【simple wxpay:简易微信支付】

初识python wxpy模块之swxpay[简易版微信支付]_第1张图片

前往测试体验

设置了0.5元测试接口的支付金额,实际使用可以自行设定即可

简单介绍一下swxpay优缺点:

优点:

  • (1)摆脱申请微信支付繁琐的步骤

    • (a)在线提交营业执照、身份证、银行账户等基本信息,并按指引完成账户验证
    • (b)微信支付团队会在1-2个工作日内完成审核,审核通过后请在线签约,即可体验各项产品能力
    • (c)如需自行开发完成收款,需将商户号与APPID进行绑定,或开通微信收款商业版(免开发)完成收款
  • (2)方便个人网站接入微信支付

  • (3)支持回调个人网站的第三方接口

  • (4)0基础实现支付开发,摆脱微信支付学习成本

缺点:

  • (1)可能无法支撑大规模支付
    • (a)可以优化提高
  • (2)需要使用一个小号进行绑定二维码收款
    • (a)原理的局限性决定的,是登录网页版微信监听实现消息实现
  • (3)服务端需要生成唯一ID传递给支付用户从而确定支付的目标订单
    • (a)通过支付备注传递
  • 需要一定的python知识
    • 非必须,因为我都写好了,贴出来即可【奸笑】
话不多说看代码实现吧…

import datetime
import time
import pymysql
import requests
from DBUtils.SimplePooledDB import PooledDB
from wxpy import *

class DaoUtil:
    def __init__(self):
        self.__pool = PooledDB(pymysql, 3, host='localhost', port=3306, user='root', passwd='123456', db='small', cursorclass = pymysql.cursors.DictCursor)

    def __get_connection(self):
        connection = self.__pool.connection()
        return connection

    def execute_sql(self, sql, is_return=False):
        connection = self.__get_connection()
        result = None
        try:
            cursor = connection.cursor() # as_dict=True
            cursor.execute(sql)
            if is_return:
                result = cursor.fetchall()
            else:
                result = True
            connection.commit()
        except Exception as e:
            print(e)
            # write log db
        finally:
            cursor.close()
            connection.close()
            return result

# ---------------------------------------------------------------------------------------------------------- #

_payid_start_str = '付款方备注'
_payid_start_str_len = len(_payid_start_str)
_payid_end_str = '汇总'

_money_start_str = '收款'
_money_start_str_len = len(_money_start_str)
_money_end_str = '元'

daoUtil = DaoUtil()

_default_headers = {
            'Accept': "*/*",
            'Accept-Language': "zh-CN,zh;q=0.8",
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive',
            'Referer': 'https://www.baidu.com',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
            'Upgrade-Insecure-Requests': '1',
        }

# bot = Bot(cache_path=True)
bot = Bot(console_qr=2, cache_path=True, qr_path='/www/server/shainesfiles/python_wx/login.png')

# @bot.register(msg_types=TEXT)
@bot.register(msg_types = SHARING)
def process_mp_wxpay(msg):
    # 只获取微信支付公众号的信息
    if str(msg.sender) == '':
        err_msg = ''

        raw = msg.raw
        # 获取消息id
        _id = raw['MsgId']
        # print('id:', _id)

        # 获取付款id
        _content = str(raw['Content'])
        payid = get_payid(_content)
        # print('payid:', payid)

        # 获取金额
        _text = str(msg.text)
        money = get_money(_text)
        if money == 0.0:
            err_msg += ' 获取金额失败'
        # print('money:', money)

        # 获取微信服务器收款时间
        createtime = str(msg.create_time)
        createtime = date_str_to_time_second(date_str = createtime)
        if createtime == 0:
            err_msg += ' 获取微信服务器创建时间失败'
        # print('createtime:', createtime)

        # 获取本地程序收款时间
        receivetime = str(msg.receive_time)
        receivetime = receivetime[0: str(receivetime).rfind('.')]
        receivetime = date_str_to_time_second(date_str = receivetime)
        if createtime == 0:
            err_msg += ' 获取本地接受时间失败'
        # print('receivetime:', receivetime)

        latency = msg.latency
        latency = str(latency)
        if len(latency) > 8:
            latency = latency[0: 8]
        latency = float(latency)
        # print('latency:', latency)

        sql = f"INSERT INTO wxpay (id, payid, money, createtime, receivetime, latency, remarks) VALUES ('{_id}', '{payid}', {money}, {createtime}, {receivetime}, {latency}, '{err_msg}')"

        # print(sql)
        daoUtil.execute_sql(sql)

        # 网络请求调用接口
        # requests.request('post', url=url, data=data, json=json, headers=_default_headers, timeout=timeout)

# ---------------------------------------------------------------------------------------------------------- #

def date_str_to_time_second(date_str='2018-08-18 09:16:36', format='%Y-%m-%d %H:%M:%S'):
    '''
    时间字符串转毫秒值
    '''
    _time_second = 0
    try:
        date_time_obj = datetime.datetime.strptime(date_str, format)
        _time_second = int(time.mktime(date_time_obj.timetuple()) * 1000)
    except:
        _time_second = 0
    return _time_second

def get_money(_text):
    '''
    解析获取money
    '''
    _money_start_index = _text.find(_money_start_str)
    _money_end_index = _text.find(_money_end_str, _money_start_index)
    money = 0.0
    try:
        money = float(_text[_money_start_index + _money_start_str_len: _money_end_index])
    except:
        money = 0.0
    return money


def get_payid(_content):
    '''
    解析获取支付id
    '''
    _payid_start_index = _content.find(_payid_start_str)
    _payid_end_index = _content.find(_payid_end_str, _payid_start_index)
    # payid = 0
    # try:
    #     payid = int(str(_content[_payid_start_index + _payid_start_str_len: _payid_end_index]).strip())
    # except:
    #     payid = 0
    # return payid
    return str(_content[_payid_start_index + _payid_start_str_len: _payid_end_index]).strip()

# ---------------------------------------------------------------------------------------------------------- #

embed()

结束语

  • 目前代码实现也就是160行左右,现在只是测试阶段,有可能还需要根据具体使用修改部分代码
  • 如果你有一定python基础的话可以拿去跑一下,但是提前告知你,肯定会有一系列问题,部署到服务器上问题测试更多的了…
  • 如果有时间的话下一篇博客有可以能会介绍如何在window and linux 服务器上部署swxpay(Simple wxpay)

博客同步到SHY BLOG

初识python wxpy模块之swxpay[简易版微信支付]_第2张图片

你可能感兴趣的:(python,学习记录,python)