def paynotify(request): ''' 微信支付异步回调 ''' data = request.body.decode('utf-8') try: wechatpay = WeChatPay(settings.WECHAT_APP_ID, settings.WECHAT_KEY, settings.WECHAT_MCH_ID) data = wechatpay.parse_payment_result(data) except InvalidSignatureException: print('微信支付异步回调签名错误') return_code = data.get('return_code') return_msg = data.get('return_msg') out_trade_no = data.get('out_trade_no') transaction_id = data.get('transaction_id') if (return_code == 'SUCCESS'): orders = AppSalesorders.objects.filter( order_id=out_trade_no, orderstatus=OrderStatus.UnPaid.value) if orders: # 订单处理 order = orders[0] order.transaction_id = transaction_id order.orderstatus = OrderStatus.Paid.value order.clientsource = 'wechat' order.paytype = 'wechat' order.paytime = timezone.now() order.save() xml = '<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>' \ .format(return_code, 'OK') return HttpResponse(xml, content_type='text/xml')
def get_payment_wechat_sign_validation(params): wechat_app_id = 'viastelle' merchant_id = 'viastelle' api_key = 'viastelle' client = WeChatPay( appid=wechat_app_id, mch_id=merchant_id, api_key=api_key, ) return client.check_signature(params)
def pay(request): ''' 微信支付 ''' user_id = request.user.id order_id = request.GET.get('order_id') try: order = AppSalesorders.objects.get( order_id=order_id, user_id=user_id, orderstatus=OrderStatus.UnPaid.value) except AppSalesorders.DoesNotExist: return HttpResponse('订单不存在') platform_user = AppPlatformUser.objects.get(user_id=user_id) wechatpay = WeChatPay(settings.WECHAT_APP_ID, settings.WECHAT_KEY, settings.WECHAT_MCH_ID) # 统一下单 unifiedorder_result = wechatpay.order.create( 'JSAPI', '社保公积金', str(int(order.pay_amount * 100)), settings.SITE_DOMAIN + 'wechat/paynotify/', user_id=platform_user.openid, out_trade_no=order_id) # 预支付订单号 prepay_id = unifiedorder_result.get('prepay_id') # 获取 JSAPI 参数 paysign_params = wechatpay.jsapi.get_jsapi_params(prepay_id) return render(request, 'wechat/jsapi.html', paysign_params)
def payment(request, *args, **kwargs): ''' 支付接口 :param request: :return: ''' # pass client = WeChatPay(appid='', api_key='', mch_id='', sub_mch_id=None, mch_cert=None, mch_key=None, timeout=None, sandbox=False) client.jsapi.get_jsapi_params(prepay_id='', timestamp=None, nonce_str=None, jssdk=False) client.jsapi.get_jsapi_signature(prepay_id='', timestamp=None, nonce_str=None) return JsonResponse({'a': 'a'})
def _get_wechatpay(self): """获取微信支付客户端""" try: # WeChatPay has no sandbox enviroment. wechatpay = WeChatPay(self.wechatpay_appid, self.wechatpay_app_key, self.wechatpay_mch_id, mch_cert=self.wechatpay_mch_cert, mch_key=self.wechatpay_mch_key) return wechatpay except Exception as err: _logger.exception(f"生成微信支付客户端失败:{err}")
def _get_wechatpay(self): """get wechatpay client""" try: # WeChatPay has no sandbox enviroment. wechatpay = WeChatPay(self.wechatpay_appid, self.wechatpay_app_key, self.wechatpay_mch_id, mch_cert=self.wechatpay_mch_cert, mch_key=self.wechatpay_mch_key) return wechatpay except Exception as err: _logger.exception(_(f"generate wechatpay client error:{err}"))
def post(self): SUCCESS, FAIL = "SUCCESS", "FAIL" web_url = utils.config.get('global', 'url') wechat_conf = utils.config.get_section('wechat') app_id = wechat_conf['appid'] key = wechat_conf['key'] mchid = wechat_conf['mchid'] mch_cert = wechat_conf['mch_cert'] mch_key = wechat_conf['mch_key'] wechat_order_client = WeChatPay(app_id, key, mchid) try: wechat_data = wechat_order_client.parse_payment_result(self.request.body) result_code = wechat_data.get('result_code', '') return_code = wechat_data.get('return_code', '') out_trade_no = wechat_data.get('out_trade_no', '') if result_code != 'SUCCESS' or return_code != 'SUCCESS' or not out_trade_no: self.logger.error('pay failed!!!') self.write(FAIL) else: order_client = wechat_order_client.order query_data = order_client.query(out_trade_no=out_trade_no) if query_data: order_models = self.model_config.all(OrderModel, user_id=1, out_trade_no=out_trade_no) for order_model in order_models: # type:OrderModel order_model.status = OrderModel.STATUS_WAIT_SEND order_model.pay_time = datetime.datetime.now() if order_models: self.model_config.commit() self.logger.info('pay success!!!') self.write(SUCCESS) else: self.logger.error('pay failed!!!') self.write(FAIL) else: self.logger.error('pay failed!!!') self.write(FAIL) # OrderedDict([(u'return_code', u'SUCCESS'), (u'return_msg', u'OK'), (u'appid', u'wx1f5f84b210348212'), (u'mch_id', u'1377692402'), (u'nonce_str', u'jLutLne3WcsmaAId'), (u'sign', u'2FEBA18A99702C3667EA3CCE838FE2AD'), (u'result_code', u'SUCCESS'), (u'openid', u'oZDZcxIVPgABuLIbLi_ZEENVRzGM'), (u'is_subscribe', u'Y'), (u'trade_type', u'JSAPI'), (u'bank_type', u'CFT'), (u'total_fee', u'1'), (u'fee_type', u'CNY'), (u'transaction_id', u'4007362001201702038556330643'), (u'out_trade_no', u'31a63b3ae9e011e6a05bfa163ec98286'), (u'attach', None), (u'time_end', u'20170203151305'), (u'trade_state', u'SUCCESS'), (u'cash_fee', u'1')]) except Exception, e: self.logger.error(e)
def wxpay(request): """ 通过小程序前端 wx.login() 接口获取临时登录凭证 code 将 code 作为参数传入,调用 get_user_info() 方法获取 openid """ code = request.GET.get("code", None) openid = get_user_info(code)['openid'] pay = WeChatPay(settings.WECHAT['APPID'], settings.WECHAT['MERCHANT_KEY'], settings.WECHAT['MCH_ID']) order = pay.order.create( trade_type = settings.WECHAT['TRADE_TYPE'], # 交易类型,小程序取值:JSAPI body = settings.WECHAT['BODY'], # 商品描述,商品简单描述 total_fee = settings.WECHAT['TOTAL_FEE'], # 标价金额,订单总金额,单位为分 notify_url = settings.WECHAT['NOTIFY_URL'], # 通知地址,异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。 user_id = openid # 用户标识,trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。 ) wxpay_params = pay.jsapi.get_jsapi_params(order['prepay_id']) return HttpResponse(json.dumps(wxpay_params))
def order_pay(request): if request.method == "POST": token = request.POST.get('token') order_id = request.POST.get('order_id') openid = get_user_info(code)['openid'] user = check_user(token) if user == {}: return JsonResponse({"code": 0, "msg": "请重新登录"}) pay = WeChatPay(config.APPINFO['appid'], settings.WECHAT['MERCHANT_KEY'], settings.WECHAT['MCH_ID']) order = pay.order.create( trade_type=config.WECHAT['TRADE_TYPE'], # 交易类型,小程序取值:JSAPI body=config.WECHAT['BODY'], # 商品描述,商品简单描述 total_fee=config.WECHAT['TOTAL_FEE'], # 标价金额,订单总金额,单位为分 notify_url=config.WECHAT['NOTIFY_URL'], user_id=openid) wxpay_params = pay.jsapi.get_jsapi_params(order['prepay_id']) order = Order.objects.get(id=order_id) order.status = 5 order.save() return JsonResponse({"code": 0, "data": "wxpay_params"})
# -*- coding:utf-8 -*- from flask import Blueprint, request, jsonify, abort from datetime import timedelta from wechatpy.pay import WeChatPay from qiniu import Auth from app import mp_client from models import Book, Post, User, CartItem, Order from ext import database as db from ext import logger, SQLAlchemyError, InvalidPostException from utils import * from config import * app = Blueprint('api_wxapp_order', __name__, url_prefix='/api/mp/order') pay_client = WeChatPay(appid=mp_APPID, api_key='ffe973955279fb3c93d9d8198a34aec7', mch_id=mch_ID) # 微信支付client # order_client = WeChatOrder(mp_client) # 传入小程序client,生成订单client q = Auth(AK, SK) bucket_name = 'bookbird' bucket_url = 'http://img.bookbird.cn/' @app.route('', methods=['GET', 'POST', 'PUT', 'DELETE']) def order(): if request.method == 'GET': token = request.args.get('token', '') order_id = request.args.get('orderId', '') user_found = User.get_by_token(token)
from django.views.decorators.csrf import csrf_exempt from django.forms.models import model_to_dict from django.conf import settings from datetime import datetime, timedelta import time from django.core import serializers from decimal import Decimal from django.utils.timezone import utc from datetime import timedelta # Create your views here. #全国省分 provice = Provice.objects.all() wechatoauth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_SECRET, settings.WECHAT_REDIRECT_URL, 'snsapi_userinfo') wechatpay = WeChatPay(settings.WECHAT_APPID, settings.WECHAT_API_KEY, settings.WECHAT_MCH_ID) #微信支付授权 def oauth(method): @wraps(method) def warpper(request, *args, **kwargs): code = request.GET.get('code') if code: try: wechatoauth.fetch_access_token(code) user_info = wechatoauth.get_user_info() except Exception as e: print e.errmsg, e.errcode else: user = None
# 支付结果 通知 if IS_PROD_ENV: CBAPI_NOTIFY = 'https://api.ifand.com/cb/wxpay' else: CBAPI_NOTIFY = 'http://xhie2s.natappfree.cc/cb/wxpay' # 支付回调返回内容 CB_RES = b"""<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>""" # 微信支付接口 WECHAT_PAY = WeChatPay( appid=WXMPA_APPID, api_key=WXPAY_KEY, mch_id=WXPAY_MCHID, ) def create_unifiedorder(openid, amount, trade_no, body='支付'): """ 统一下单接口 """ body = body if IS_PROD_ENV else f'【测试-{RUN_ENV}】{body}' resp_dic = WECHAT_PAY.order.create( 'JSAPI', body, amount, CBAPI_NOTIFY, user_id=openid, out_trade_no=trade_no, )
\'hideAllNonBaseMenuItem\', \'showAllNonBaseMenuItem\', ] }); ''' ApiKey = "Kp1b4lH5z3n0DqGxu2IcQsV6F7PUWvmZ" MchID = "1491203572" NotifyUrl = "http://wechat.onmytarget.cn/payback" client = WeChatClient(AppId, AppSecret) jsApiClient = WeChatJSAPI(client=client) mediaApiClient = WeChatMedia(client=client) payClient = WeChatPay(appid=AppId, api_key=ApiKey, mch_id=MchID, mch_cert=os.path.join(settings.BASE_DIR, 'carcert', 'apiclient_cert.pem'), mch_key=os.path.join(settings.BASE_DIR, 'carcert', 'apiclient_key.pem')) oauthClient = WeChatOAuth(app_id=AppId, secret=AppSecret, redirect_uri=DOMAIN) def get_wechat_config(request): """ 获取微信config字符串 :param request: :return: """ timestamp = to_text(int(time.time())) nonce_str = random_string(32) jsapi_ticket = jsApiClient.get_jsapi_ticket()
def wxapp(self, sub_domain, **kwargs): token = kwargs.pop('token', None) try: res, wechat_user, entry = self._check_user(sub_domain, token) if res: return res #weixin = request.env['payment.acquirer'].sudo().search([('provider', '=', 'weixin')]) _logger.info('>>> order_dict%s, %s, %s', res, wechat_user, entry) weixin = entry #request.env['wxapp.config'].sudo().search([])[0] _logger.info('>>> order_dict %s,[%s,%s,%s,%s]', weixin, weixin.wechat_pay_id, weixin.wechat_pay_secret, weixin.app_id, weixin.secret) # [{"goodsId":1,"number":3,"propertyChildIds":"1:1,2:4,","logisticsType":0, "inviter_id":0}] money = int(kwargs.pop('money')) remark = kwargs.pop('remark', '') payName = kwargs.pop('payName', '') nextAction = json.loads(kwargs.pop('nextAction')) _logger.info('>>> order_dict [%s,%s,%s,%s]', money, remark, payName, nextAction) from wechatpy.pay import WeChatPay pay = WeChatPay(appid=weixin.app_id, api_key=weixin.wechat_pay_secret, mch_id=weixin.wechat_pay_id, sub_appid=weixin.app_id) res = pay.order.create( trade_type="JSAPI", body=payName, total_fee=money, user_id=wechat_user.open_id, notify_url='http://www.daotismart.com/%s/pay/wx/callback' % (sub_domain)) _logger.info('>>> order_dict %s', res) prepay_id = res.get("prepay_id") statusValue = { 'SUCCESS': defs.PaymentStatus.success, 'FAIL': defs.PaymentStatus.fail } payment = { "openid": wechat_user.open_id, "order_id": nextAction['id'], "payment_number": prepay_id, "result_code": res.get("result_code"), "settlement_total_fee": money, "total_fee": money, "transaction_id": prepay_id, "wechat_user_id": wechat_user.id, "status": statusValue[res.get("result_code")] } request.env(user=1)['wxapp.payment'].create(payment) order = request.env['sale.order'].sudo().search([ ('partner_id', '=', wechat_user.partner_id.id), ('id', '=', int(nextAction['id'])) ]) if not order: return self.res_err(404) order.check_paid() #order.write({'customer_status': 'padding'}) params = { "appId": weixin.app_id, "timeStamp": str(int(time.time())), "nonceStr": ''.join(random.sample(string.ascii_letters + string.digits, 32)), "package": 'prepay_id=%s' % (prepay_id), "signType": "MD5", } strs = '&'.join([ '{}={}'.format(key, params.get(key)) for key in sorted(params.keys()) if params.get(key) ]) + "&key={}".format(weixin.wechat_pay_secret) _logger.info('>>> strs:[%s]', strs) paySign = md5(strs.encode("utf-8")).hexdigest().upper() params['sign'] = paySign return self.res_ok(params) except Exception as e: _logger.exception(e) return self.res_err(-1, e.name)
from kele import settings from .models import Goods, Order, OrderItem, ShopCart, MemberScore ,MemberScoreDetail, ScoresLimit, MailFee, \ MemberRechargeAmount, MemberRechargeRecord, MemberDeposit, MarketPlan from petfoster.models import FosterStyleChoose from wxchat.decorators import weixin_decorator from wxchat.utils import random_number from wxchat.views import getJsApiSign, sendTempMessageToUser, sendPasswordTemplateMesToUser, sendChargeSuccessToUser from wechatpy.pay import WeChatPay from wechatpy.pay.utils import dict_to_xml from wxchat.models import WxUserinfo, WxUnifiedOrderResult, WxPayResult, WxIntroduce, WxTemplateMsgUser from wechatpy.exceptions import WeChatPayException, InvalidSignatureException from django.db.models import Sum, F, FloatField, Count, Q wxPay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.MCH_KEY, mch_id=settings.MCH_ID) def resetPassword(deposit): newpasswd = random_number() new_password = make_password(newpasswd) deposit.password = new_password deposit.pwd_time = datetime.now() deposit.save() # 发送密码给用户 deposit.new_password = newpasswd print(newpasswd, new_password) sendPasswordTemplateMesToUser(deposit, mode=0)
# 这里吃的大亏,回调地址不能用 https , f**k http_root = config.get('HTTP_ROOT') notify_url = http_root + '/wx/pay/notifyurl' mch_key = config.get('WECHAT_MCH_KEY') """ appid – 微信公众号/或者小程序号 api_key – 商户 key, 不要在这里使用小程序的密钥 mch_id – 商户号 (sub_mch_id – 可选,子商户号,受理模式下必填,这里不填) (mch_cert – 商户证书路径,这里不填) mch_key – 必填,商户证书私钥路径(小程序,这里也填商户号key) timeout – 可选,请求超时时间,单位秒,默认无超时设置 sandbox – 可选,是否使用测试环境,默认为 False """ wx_pay = WeChatPay(appid=mp_id, mch_id=mp_mch_id, mch_key=mp_mch_key, api_key=mp_mch_key) # 微信的签名逻辑需要注意: # # 商户密钥不参与字典序排序 # md5后需要转大写 # 参与排序的字典名要与微信的文档严格保持一致 @bp.route("/reqPay", methods=["POST", "GET"]) def get_json1(): print(request.args) # 这里还有一个 请求 sign 的构造过程, wechatpy 都已经封装好了 rs = wx_pay.order.create(trade_type="JSAPI", total_fee=1, # 订单总金额,单位为分 notify_url=notify_url, # 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的 http 地址,不能是 https ,不能携带参数。 user_id=request.args.get("openid"), # 微信分配的小程序ID,擦嘞
def create_wechatpay_client(): return WeChatPay(settings.WECHAT_APP_ID, settings.WECHAT_API_KEY, settings.WECHAT_MCH_ID)
def pay_feedback(request): mch_id = '1571816511' mch_key = 'qingjiaorenlingshop2019111820000' appid = 'wx5aff52c0a3a0f7ac' xml = request.body.decode('utf-8') wepy_order = WeChatPay(appid=appid, sub_appid=appid, api_key=mch_key, mch_id=mch_id) result = wepy_order.parse_payment_result(xml) prepay = ZxPrepay_Order.objects.get(out_trade_no=result['out_trade_no']) prepay_serializer = ZxPrepay_OrderSerializer(prepay, many=False) # print('prepay_serializer',prepay_serializer.data) if prepay_serializer.data['varified'] == True: # print('varified==True') return HttpResponse('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>') # print('fee,',float(prepay_serializer.data['fee']),float(result['total_fee'])) if (float(prepay_serializer.data['fee'])*100 == float(result['total_fee'])): # print('sign=sign&fee=fee') item = ZxItem.objects.get(id=prepay_serializer.data['item_id']) wxuser = ZxUser.objects.get( user_openid=prepay_serializer.data['openid']) item_serializer = ZxItemSerializer(item, many=False) new_order = ZxOrder.objects.create( num=str(prepay_serializer.data['out_trade_no']), item=item, farm_name=item.owner.farm_name, wxuser=wxuser, deliver_address=prepay_serializer.data['deliver_address'], price_paid=prepay_serializer.data['fee'], quantity=prepay_serializer.data['quantity'], price_origin=item_serializer.data['item_price'], imageUrl=item_serializer.data['pic_address'], phone_num=str(prepay_serializer.data['phone_num']), name_rec=prepay_serializer.data['name_rec'], captain_id=prepay_serializer.data['captain_id'], deliver_time=prepay_serializer.data['deliver_time'], ) comment = ZxComments.objects.create( zxuser=wxuser, comment_text='我刚刚买了'+item.item_name+'!', item_id=item.item_id, user_avatar=wxuser.user_avatar, user_nickname=wxuser.user_nickname, genre=2, ) #print('order created:',new_order) prepay.varified = True prepay.save() #print('prepay varified') return HttpResponse('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>') else: failed = ZxVarify_failed.objects.create( fee=prepay_serializer.data['fee'], out_trade_no=prepay_serializer.data['out_trade_no'], ) return HttpResponse('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[金额错误]]></return_msg></xml>')
def weChatPay(request): mch_id = '1571816511' mch_key = 'qingjiaorenlingshop2019111820000' appid = 'wxd647f4c25673f368' secret = '7de75de46a3d82dcc0bed374407f310f' code = request.GET.get('code') item_id = request.GET.get('item_id') item_name = request.GET.get('item_name') item_price = request.GET.get('item_price') num_buy = int(request.GET.get('num_buy')) reward = request.GET.get('reward') price = int(float(request.GET.get('total_fee')) * 100) address = request.GET.get('addRegion') + request.GET.get('addDetail') nickname = request.GET.get('nickname') post_sign = request.GET.get('post_sign') name_rec = request.GET.get('name_rec') phone_num = request.GET.get('phone_num') tree_ip = get_treeip(item_id) NOTIFY_URL = 'https://qingjiao.shop:8000/dataserver/pay_feedback' wxLoginURL = 'https://api.weixin.qq.com/sns/jscode2session?' + 'appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=' + 'authorization_code' res = json.loads(requests.get(wxLoginURL).content) nonceStr = pay.getNonceStr() if 'errcode' in res: return Response(data={ 'code': response['errcode'], 'msg': response['errmsg'] }) ##success openid = res['openid'] wxuser = WxUser.objects.get_or_create(user_openid=openid, ) wepy_order = WeChatPay(appid=appid, sub_appid=appid, api_key=mch_key, mch_id=mch_id) out_trade_no = pay.getWxPayOrdrID() pay_res = wepy_order.order.create( trade_type="JSAPI", body=item_name, total_fee=price, notify_url=NOTIFY_URL, user_id=openid, out_trade_no=out_trade_no, ) prepay_id = pay_res.get("prepay_id") wepy_sign = wepy_order.order.get_appapi_params(prepay_id=prepay_id) timeStamp = str(int(time.time())) nonceStr = pay_res['nonce_str'] paySign = pay.get_paysign(prepay_id=prepay_id, timeStamp=timeStamp, nonceStr=nonceStr) prepay_order = Prepay_Order.objects.create( out_trade_no=out_trade_no, sign=paySign, noncestr=nonceStr, openid=openid, fee=int(price) / 100, ##cents deliver_address=address, quantity=num_buy, buyernickname=nickname, postsign=post_sign, item_id=int(item_id), phone_num=str(phone_num), name_rec=name_rec, ) #print("------paySign:",paySign) return Response( data={ 'wepy_sign': wepy_sign, 'status': 100, 'paySign': paySign, 'timeStamp': timeStamp, 'nonceStr': nonceStr })
def pay_feedback(request): mch_id = '1571816511' mch_key = 'qingjiaorenlingshop2019111820000' appid = 'wxd647f4c25673f368' xml = request.body.decode('utf-8') wepy_order = WeChatPay(appid=appid, sub_appid=appid, api_key=mch_key, mch_id=mch_id) result = wepy_order.parse_payment_result(xml) #print('pay_result:',result) prepay = Prepay_Order.objects.get(out_trade_no=result['out_trade_no']) prepay_serializer = Prepay_OrderSerializer(prepay, many=False) #print('prepay_serializer',prepay_serializer.data) if prepay_serializer.data['varified'] == True: #print('varified==True') return HttpResponse( '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>' ) #print('fee,',float(prepay_serializer.data['fee']),float(result['total_fee'])) if (float(prepay_serializer.data['fee']) * 100 == float( result['total_fee'])): #print('sign=sign&fee=fee') item = Item.objects.get(id=prepay_serializer.data['item_id']) wxuser = WxUser.objects.get( user_openid=prepay_serializer.data['openid']) item_serializer = ItemSerializer(item, many=False) new_tree = get_treeip(item_id=item.id) region_name = new_tree["region_name"] r = new_tree['row'] l = new_tree['line'] i = new_tree['i'] tree_ip = region_name + "-" + str(l) + '行' + str(r) + "列" update_region_status(region_name=region_name, r=r, l=l, new_status=1, i=i) new_order = Order.objects.create( num=str(prepay_serializer.data['out_trade_no']), item=item, wxuser=wxuser, deliver_address=prepay_serializer.data['deliver_address'], price_paid=prepay_serializer.data['fee'], quantity=prepay_serializer.data['quantity'], buyernickname=prepay_serializer.data['buyernickname'], postsign=prepay_serializer.data['postsign'], price_origin=item_serializer.data['item_price'], tree_ip=tree_ip, benefit=item_serializer.data['item_benefit'], guaranteed=item_serializer.data['item_guaranteed'], imageUrl=item_serializer.data['pic_address'], phone_num=str(prepay_serializer.data['phone_num']), name_rec=prepay_serializer.data['name_rec'], ip_row=r, ip_line=l, ) #print('order created:',new_order) prepay.varified = True prepay.save() #print('prepay varified') return HttpResponse( '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>' ) else: failed = Varify_failed.objects.create( fee=prepay_serializer.data['fee'], out_trade_no=prepay_serializer.data['out_trade_no'], ) return HttpResponse( '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[金额错误]]></return_msg></xml>' )
import string import json from wechatpy.pay import WeChatPay from wechatpy.pay.api import WeChatOrder from wechatpy.pay.api import WeChatJSAPI from wx_config import WxConfig from wx_api import wechat_client from utils.log import logger weChatPay = WeChatPay( WxConfig.AppID, WxConfig.ApiKey, WxConfig.MchId, sub_mch_id = None, mch_cert = WxConfig.MchCert, mch_key = WxConfig.MchKey, timeout = 10, ) weChatOrder = WeChatOrder(weChatPay) weChatJSAPI = WeChatJSAPI(weChatPay) notify_url = 'http://m.91kage.com/pay/create/result' # 统一下单接口 def CreateWeChatOrder(notifyUrl, totalFee, clientIp, openId, orderId, detail): attach = json.dumps({'openId': openId, 'orderId':orderId}) ret = weChatOrder.create( 'JSAPI', # trade_type u'91卡哥金服-会员充值', # body totalFee, # total_fee 1块钱,单位分
class WePay(object): we_pay = WeChatPay( appid=settings.MP_APP_ID, api_key=settings.MP_APP_KEY, mch_id=settings.MP_MERCHANT_ID, sub_mch_id=None if not settings.MP_SUB_MERCHANT_ID else settings.MP_SUB_MERCHANT_ID, mch_cert=settings.MP_MERCHANT_CERT, mch_key=settings.MP_MERCHANT_KEY, timeout=10, sandbox=settings.MP_PAY_SANDBOX, ) @classmethod def is_right_sign(cls, params) -> bool: return cls.we_pay.check_signature(params) class TradeState(ModelEnum): PAID = 'SUCCESS' # 支付成功 REFUND = 'REFUND' # 转入退款 NOTPAY = 'NOTPAY' # 未支付 CLOSED = 'CLOSED' # 已关闭 REVOKED = 'REVOKED' # 已撤销. (付款码支付) USERPAYING = 'USERPAYING' # 用户支付中. (付款码支付) PAYERROR = 'PAYERROR' # 支付失败. (其他原因,如银行返回失败) @classmethod def create_jsapi_order(cls, out_trade_no, total_fee, title, openid, client_ip, attach=None, notify_url=None): """ 用户点击button跳转到收银台支付. :param out_trade_no: :param total_fee: 支付金额, 单位分 :param title: 订单标题 :param openid: 缴费用户的openid. 当trade_type=JSAPI, 此参数必传, 且是授权给公众号的用户openid :param client_ip: APP和网页支付提交用户端ip, Native支付填调用微信支付API的机器IP :param attach: 用户自定义数据,在notify的时候会原样返回 :param notify_url: 接收微信支付异步通知的回调地址。必须为可直接访问的URL,不能带参数、session验证、csrf验证。不能留空! """ # 统一下单. 微信官方参数地址: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 order_params = { 'trade_type': 'JSAPI', # 交易类型 JSAPI--公众号支付, NATIVE--原生扫码支付, APP--app支付, 而MICROPAY--刷卡支付有单独的支付接口, 不能调用统一下单接口 'body': title, # 商品描述 'total_fee': total_fee, # 订单金额. (单位分) 'attach': attach, 'user_id': openid, # 可选. 缴费用户的openid. 当trade_type=JSAPI, 此参数必传 'client_ip': client_ip, # 可选. APP和网页支付提交用户端ip, Native支付填调用微信支付API的机器IP 'out_trade_no': out_trade_no, 'detail': None, # 可选, 商品详情 'fee_type': 'CNY', # 可选, 符合ISO 4217标准的三位字母代码, 默认人民币: CNY 'time_start': None, # 可选, 订单生成时间, 默认为当前时间 'time_expire': None, # 可选, 订单失效时间, 默认为订单生成时间后两小时 'goods_tag': None, # 可选, 商品标记, 代金券或立减优惠功能的参数 'product_id': None, # 可选, 当trade_type=NATIVE, 此参数必传. 此id为二维码中包含的商品ID, 商户自行定义 'device_info': None, # 可选, 终端设备号(门店号或收银设备ID), 注意:PC网页或公众号内支付请传"WEB" 'limit_pay': None, # 可选, 指定支付方式, no_credit-指定不能使用信用卡支付 'notify_url': notify_url, # 订单通知地址 } # 统一下单, 生成微信支付参数返回给微信浏览器 response = cls.we_pay.order.create(**order_params) # OrderedDict([('return_code', 'SUCCESS'), # ('return_msg', 'OK'), # ('appid', 'wx14d296959ee50c0b'), # ('mch_id', '1517154171'), # ('nonce_str', 'RDX6pxz2GTEdoQnE'), # ('sign', '796CC22F8EDD664372BE9ACF7EB68ACD'), # ('result_code', 'SUCCESS'), # ('prepay_id', 'wx242238115691612efb08d4092661275602'), # ('trade_type', 'JSAPI')]) return response @classmethod def create_native_order(cls, out_trade_no, total_fee, title, product_id, client_ip, attach=None, notify_url=None): """ 用户扫码支付. :param out_trade_no: :param total_fee: 支付金额, 单位分 :param title: 订单标题 :param product_id: 当trade_type=NATIVE, 此参数必传. 此id为二维码中包含的商品ID, 商户自行定义. (实测None也可以) :param client_ip: APP和网页支付提交用户端ip, Native支付填调用微信支付API的机器IP :param attach: 用户自定义数据,在notify的时候会原样返回 :param notify_url: 接收微信支付异步通知的回调地址。必须为可直接访问的URL,不能带参数、session验证、csrf验证。不能留空! """ # 统一下单. 微信官方参数地址: https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1 order_params = { 'trade_type': 'NATIVE', # 交易类型 JSAPI--公众号支付, NATIVE--原生扫码支付, APP--app支付, 而MICROPAY--刷卡支付有单独的支付接口, 不能调用统一下单接口 'body': title, # 商品描述 'total_fee': total_fee, # 订单金额. (单位分) 'attach': attach, 'user_id': None, # 可选. 缴费用户的openid. 当trade_type=JSAPI, 此参数必传 'client_ip': client_ip, # 可选. APP和网页支付提交用户端ip, Native支付填调用微信支付API的机器IP 'out_trade_no': out_trade_no, 'detail': None, # 可选, 商品详情 'fee_type': 'CNY', # 可选, 符合ISO 4217标准的三位字母代码, 默认人民币: CNY 'time_start': None, # 可选, 订单生成时间, 默认为当前时间 'time_expire': None, # 可选, 订单失效时间, 默认为订单生成时间后两小时 'goods_tag': None, # 可选, 商品标记, 代金券或立减优惠功能的参数 'product_id': product_id, # 可选, 当trade_type=NATIVE, 此参数必传. 此id为二维码中包含的商品ID, 商户自行定义 'device_info': None, # 可选, 终端设备号(门店号或收银设备ID), 注意:PC网页或公众号内支付请传"WEB" 'limit_pay': None, # 可选, 指定支付方式, no_credit-指定不能使用信用卡支付 'notify_url': notify_url, # 订单通知地址 } # 统一下单, 生成微信支付参数返回给微信浏览器 response = cls.we_pay.order.create(**order_params) # OrderedDict([('return_code', 'SUCCESS'), # ('return_msg', 'OK'), # ('appid', 'wx54d296959ee50c01'), # ('mch_id', '1517154171'), # ('nonce_str', 'IvST3Mh4a5cQEUdN'), # ('sign', 'BF402367D8C84BE53D0DCE942FA676AB'), # ('result_code', 'SUCCESS'), # ('prepay_id', 'wx27163152798783d24f7f81121395790900'), # ('trade_type', 'NATIVE'), # ('code_url', 'weixin://wxpay/bizpayurl?pr=LQjaKQI')]) return response @classmethod def get_jsapi_params(cls, prepay_id: str): """ :param prepay_id: :return: # {'appId': 'wx54d296959ee50c01', # 'nonceStr': '603sd7IpN4M2OqCVvZazxrXY9bT5lBcR', # 'package': 'prepay_id=wx242238115691612efb08d4092661275602', # 'paySign': '6D2340AC7276C93852461E130A404E87', # 'signType': 'MD5', # 'timeStamp': '1540391991'} """ params = cls.we_pay.jsapi.get_jsapi_params(str(prepay_id)) return params @classmethod def apply_refund(cls, out_trade_no, total_fee, out_refund_no, refund_fee, notify_url=None): """ 微信侧保证全额退款最多只会执行1次 """ refund_params = { 'total_fee': total_fee, # 订单总金额,单位为分 'refund_fee': refund_fee, # 退款总金额,单位为分 'out_refund_no': out_refund_no, # 商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔 'out_trade_no': out_trade_no, # 商户系统内部的订单号,transaction_id 二选一 'fee_type': 'CNY', # 可选,货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY 'notify_url': notify_url, # 可选,异步接收微信支付退款结果通知的回调地址 } response = cls.we_pay.refund.apply(**refund_params) # >>> print(response) # OrderedDict([('return_code', 'SUCCESS'), # ('return_msg', 'OK'), # ('appid', 'wx54d296959ee50c01'), # ('mch_id', '1517154171'), # ('nonce_str', '9GgtDUrqZSiNXV7h'), # ('sign', 'E84B63245169A008C8385567E2C49AD6'), # ('result_code', 'SUCCESS'), # ('transaction_id', '4200000297201907025906623815'), # ('out_trade_no', '1562071838292kQBS1WdoVtkRGUqRW'), # ('out_refund_no', '1562071838292kQBS1WdoVtkRGUqRW'), # ('refund_id', '50000700772019070310374962187'), # ('refund_channel', None), # ('refund_fee', '1'), # ('coupon_refund_fee', '0'), # ('total_fee', '1'), # ('cash_fee', '1'), # ('coupon_refund_count', '0'), # ('cash_refund_fee', '1')]) return response @classmethod def query_order(cls, out_trade_no): """ 接口文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2 :param out_trade_no: :return: 字典类型 <xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> <appid><![CDATA[wx2421b1c4370ec43b]]></appid> <mch_id><![CDATA[10000100]]></mch_id> <device_info><![CDATA[1000]]></device_info> <nonce_str><![CDATA[TN55wO9Pba5yENl8]]></nonce_str> <sign><![CDATA[BDF0099C15FF7BC6B1585FBB110AB635]]></sign> <result_code><![CDATA[SUCCESS]]></result_code> <openid><![CDATA[oUpF8uN95-Ptaags6E_roPHg7AG0]]></openid> <is_subscribe><![CDATA[Y]]></is_subscribe> <trade_type><![CDATA[MICROPAY]]></trade_type> <bank_type><![CDATA[CCB_DEBIT]]></bank_type> <total_fee>1</total_fee> <fee_type><![CDATA[CNY]]></fee_type> <transaction_id><![CDATA[1008450740201411110005820873]]></transaction_id> <out_trade_no><![CDATA[1415757673]]></out_trade_no> <attach><![CDATA[订单额外描述]]></attach> <time_end><![CDATA[20141111170043]]></time_end> <trade_state><![CDATA[SUCCESS]]></trade_state> </xml> """ query_params = { 'out_trade_no': out_trade_no, } try: response = cls.we_pay.order.query(**query_params) return response except WeChatPayException as e: if e.errcode == 'ORDERNOTEXIST': return None raise e @classmethod def close_order(cls, out_trade_no): query_params = { 'out_trade_no': out_trade_no, } response = cls.we_pay.order.close(**query_params) return response @classmethod def parse_payment_result(cls, xml): return cls.we_pay.parse_payment_result(xml)
def weChatPay(request): ## appid = 'wx5aff52c0a3a0f7ac' secret = '3c6eb61f23aeff10038a74ff10aedd11' mch_id = '1571816511' mch_key = 'qingjiaorenlingshop2019111820000' code = request.GET.get('code') item_id = request.GET.get('item_id') item_name = request.GET.get('item_name') item_price = request.GET.get('item_price') num_buy = int(request.GET.get('num_buy')) reward = request.GET.get('reward') price = int(float(request.GET.get('total_fee'))*100) address = request.GET.get('addRegion')+request.GET.get('addDetail') name_rec = request.GET.get('name_rec') phone_num = request.GET.get('phone_num') captain_id = request.GET.get('captain_id') del_time = request.GET.get('del_time') # success wxuser = wxlogin(code) openid = wxuser.user_openid NOTIFY_URL = 'https://qingjiao.shop:8000/zxserver/pay_feedback' wepy_order = WeChatPay(appid=appid, sub_appid=appid, api_key=mch_key, mch_id=mch_id) out_trade_no = pay.getWxPayOrdrID() pay_res = wepy_order.order.create( trade_type="JSAPI", body=item_name, total_fee=price, notify_url=NOTIFY_URL, user_id=openid, out_trade_no=out_trade_no, ) # print("------pay_res",pay_res) prepay_id = pay_res.get("prepay_id") wepy_sign = wepy_order.order.get_appapi_params(prepay_id=prepay_id) # print('------wepy_sign:',wepy_sign) timeStamp = str(int(time.time())) nonceStr = pay_res['nonce_str'] paySign = pay.get_paysign( prepay_id=prepay_id, timeStamp=timeStamp, nonceStr=nonceStr) prepay_order = ZxPrepay_Order.objects.create( out_trade_no=out_trade_no, sign=paySign, noncestr=nonceStr, openid=openid, fee=int(price)/100, # cents deliver_address=address, quantity=num_buy, item_id=int(item_id), phone_num=str(phone_num), name_rec=name_rec, captain_id=captain_id, deliver_time=del_time, ) wxuser.current_captain_id = captain_id wxuser.save() return Response(data={'wepy_sign': wepy_sign, 'status': 100, 'paySign': paySign, 'timeStamp': timeStamp, 'nonceStr': nonceStr})