Skip to content

Commit

Permalink
完成微信支付接口
Browse files Browse the repository at this point in the history
  • Loading branch information
elfgzp committed Aug 21, 2017
1 parent ad81c3b commit 829f740
Show file tree
Hide file tree
Showing 21 changed files with 2,630 additions and 15 deletions.
90 changes: 78 additions & 12 deletions controllers/payment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-

import time
import json
import xmltodict

Expand All @@ -9,13 +10,34 @@
from .error_code import error_code
from .. import defs

from weixin.pay import WeixinPay
from ..weixin.pay import WeixinPay
from ..weixin.helper import md5_constructor as md5

import logging

_logger = logging.getLogger(__name__)


def build_pay_sign(app_id, nonce_str, prepay_id, time_stamp, key, signType='MD5'):
"""
:param app_id:
:param nonce_str:
:param prepay_id:
:param time_stamp:
:param key:
:param signType:
:return:
"""
sign = 'appId={app_id}' \
'&nonceStr={nonce_str}' \
'&package=prepay_id={prepay_id}' \
'&signType={signType}' \
'&timeStamp={time_stamp}' \
'&key={key}'.format(app_id=app_id, nonce_str=nonce_str, prepay_id=prepay_id,
time_stamp=time_stamp, key=key, signType=signType)
return md5(sign).hexdigest().upper()


class MakePayment(http.Controller):
@http.route('/<string:sub_domain>/pay/wxapp/get-pay-data',
auth='public', methods=['POST'], csrf=False, type='http')
Expand All @@ -25,23 +47,23 @@ def post(self, sub_domain, **kwargs):
if not user:
return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

config = self.env['wechat_mall.config.settings']
config = request.env(user=user.id)['wechat_mall.config.settings']
app_id = config.get_config('app_id', uid=user.id)
wechat_pay_id = config.get_config('wechat_pay_id', uid=user.id)
wechat_pay_secret = config.get_config('wechat_pay_id', uid=user.id)
wechat_pay_secret = config.get_config('wechat_pay_secret', uid=user.id)

if not app_id:
return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

if not wechat_pay_id or wechat_pay_secret:
if not wechat_pay_id or not wechat_pay_secret:
return request.make_response(json.dumps({'code': 404, 'msg': '未设置wechat_pay_id和wechat_pay_secret'}))

if 'token' not in kwargs.keys():
return request.make_response(json.dumps({'code': 300, 'msg': error_code[300].format('token')}))

token = kwargs.pop('token')

args_key_set = {'token', 'order_id', 'money'}
args_key_set = {'order_id', 'money'}

missing_args_key = args_key_set - set(kwargs.keys())
if missing_args_key:
Expand All @@ -63,8 +85,52 @@ def post(self, sub_domain, **kwargs):
if not wechat_user:
return request.make_response(json.dumps({'code': 10000, 'msg': error_code[10000]}))

payment = request.env(user=user.id)['wechat_mall.payment'].create({
'order_id': int(kwargs['order_id']),
'wechat_user_id': wechat_user.id,
'price': float(kwargs['money'])
})

mall_name = config.get_config('mall_name', uid=user.id) or '微信小程序商城'
base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url')
wxpay = WeixinPay(appid=app_id, mch_id=wechat_pay_id, partner_key=wechat_pay_secret)
unified_order = wxpay.unifiedorder(
body=u'{mall_name}'.format(mall_name=mall_name),
total_fee=int(float(kwargs['money']) * 100),
notify_url=u'{base_url}/{sub_domain}/pay/notify'.format(base_url=base_url, sub_domain=sub_domain),
openid=u'{}'.format(wechat_user.open_id),
out_trade_no=u'{}'.format(payment.order_id.order_num)

)
if unified_order['return_code'] == 'SUCCESS' and not unified_order['result_code'] == 'FAIL':
time_stamp = str(int(time.time()))
response = request.make_response(
headers={
"Content-Type": "json"
},
data=json.dumps({
"code": 0,
"data": {
'timeStamp': str(int(time.time())),
'nonceStr': unified_order['nonce_str'],
'prepayId': unified_order['prepay_id'],
'sign': build_pay_sign(app_id, unified_order['nonce_str'], unified_order['prepay_id'],
time_stamp, wechat_pay_secret)
},
"msg": "success"
})
)
else:
if unified_order['err_code'] == 'ORDERPAID':
payment.order_id.write({'status': 'pending'})
mail_template = request.env.ref('wechat_mall.wechat_mall_order_paid')
mail_template.sudo().send_mail(payment.order_id.id, force_send=True, raise_exception=False)

return request.make_response(
json.dumps({'code': -1, 'msg': unified_order.get('err_code_des', unified_order['return_msg'])})
)

return response
except Exception as e:
_logger.exception(e)
return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))
Expand All @@ -83,8 +149,8 @@ def post(self, sub_domain, **kwargs):
},
data=xmltodict.unparse({
'xml': {
'return_code': 'FAIL',
'return_msg': '参数格式校验错误'
u'return_code': 'FAIL',
u'return_msg': '参数格式校验错误'
}
})
)
Expand All @@ -96,7 +162,7 @@ def post(self, sub_domain, **kwargs):
data.update({'status': defs.PaymentStatus.success})
payment = request.env(user=user.id)['wechat_mall.payment'].search([
('payment_number', '=', data['out_trade_no'])
])
])
payment.write(data)
payment.order_id.write({'status': defs.OrderStatus.pending})
mail_template = request.env.ref('wechat_mall.wechat_mall_order_paid')
Expand All @@ -114,8 +180,8 @@ def post(self, sub_domain, **kwargs):
},
data=xmltodict.unparse({
'xml': {
'return_code': 'SUCCESS',
'return_msg': 'SUCCESS'
'return_code': u'SUCCESS',
'return_msg': u'SUCCESS'
}
})
)
Expand All @@ -129,8 +195,8 @@ def post(self, sub_domain, **kwargs):
},
data=xmltodict.unparse({
'xml': {
'return_code': 'FAIL',
'return_msg': '服务器内部错误'
'return_code': u'FAIL',
'return_msg': u'服务器内部错误'
}
})
)
Expand Down
1 change: 1 addition & 0 deletions models/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Order(models.Model):
_description = u'订单'
_inherit = ['mail.thread']
_rec_name = 'order_num'
_order = 'create_date desc'

wechat_user_id = fields.Many2one('wechat_mall.user', string='微信用户')
order_num = fields.Char('订单号', index=True)
Expand Down
4 changes: 2 additions & 2 deletions models/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Payment(models.Model):
order_id = fields.Many2one('wechat_mall.order', string='订单')
payment_number = fields.Char('支付单号', index=True)
wechat_user_id = fields.Many2one('wechat_mall.user', string='微信用户')
price = fields.Float('支付金额')
price = fields.Float('支付金额(元)')
status = fields.Selection(defs.PaymentStatus.attrs.items(), '状态',
default=defs.PaymentStatus.unpaid)

Expand All @@ -39,5 +39,5 @@ class Payment(models.Model):

@api.model
def create(self, vals):
vals['payment_num'] = self.env['ir.sequence'].next_by_code('wechat_mall.payment_num')
vals['payment_number'] = self.env['ir.sequence'].next_by_code('wechat_mall.payment_num')
return super(Payment, self).create(vals)
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
python-weixin==0.2.0
pycrypto==2.6.1
itsdangerous==0.24
kdniao==0.1.2
Expand Down
2 changes: 2 additions & 0 deletions security/ir.model.access.csv
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ id_access_wechat_mall_address,name_access_wechat_mall_address,model_wechat_mall_
id_access_wechat_mall_order,name_access_wechat_mall_order,model_wechat_mall_order,,1,0,0,0
id_access_wechat_mall_order_goods,name_access_wechat_mall_order_goods,model_wechat_mall_order_goods,,1,0,0,0
id_access_wechat_mall_shipper,name_access_wechat_mall_shipper,model_wechat_mall_shipper,,1,0,0,0
id_access_wechat_mall_payment,name_access_wechat_mall_payment,model_wechat_mall_payment,,1,0,0,0
id_access_ir_attachment,name_access_ir_attachment,model_ir_attachment,,1,0,0,0
,,,,,,
,,,,,,
Expand All @@ -42,4 +43,5 @@ group_wechat_mall_user_access_wechat_mall_address,group_wechat_mall_user_access_
group_wechat_mall_user_access_wechat_mall_order,group_wechat_mall_user_access_wechat_mall_order,model_wechat_mall_order,wechat_mall.group_wechat_mall_user,1,1,1,1
group_wechat_mall_user_access_wechat_mall_order_goods,group_wechat_mall_user_access_wechat_mall_order_goods,model_wechat_mall_order_goods,wechat_mall.group_wechat_mall_user,1,1,1,0
group_wechat_mall_user_access_wechat_mall_shipper,group_wechat_mall_user_access_wechat_mall_shipper,model_wechat_mall_shipper,wechat_mall.group_wechat_mall_user,1,0,0,0
group_wechat_mall_user_access_wechat_mall_payment,group_wechat_mall_user_access_wechat_mall_payment,model_wechat_mall_payment,wechat_mall.group_wechat_mall_user,1,1,1,0
group_wechat_mall_user_access_ir_attachment,group_wechat_mall_user_access_ir_attachment,model_ir_attachment,wechat_mall.group_wechat_mall_user,1,1,1,1
12 changes: 12 additions & 0 deletions weixin/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-

__title__ = 'requests'
__version__ = '0.0.2'
__author__ = 'Zongxiao Cheng'
__license__ = 'BSD'


from .bind import WeixinClientError, WeixinAPIError
from .client import WeixinAPI, WeixinMpAPI, WXAPPAPI
from .response import WXResponse
from .reply import WXReply
Loading

0 comments on commit 829f740

Please sign in to comment.