#!/usr/bin/env python # encoding: utf-8 ''' Created on 2011-1-5 @author: codeback@gmail.com ''' import hashlib import urllib2 verfyURL={ "https":"https://www.alipay.com/cooperate/gateway.do?service=notify_verify", "http" :"http://notify.alipay.com/trade/notify_query.do?", } gateway="https://www.alipay.com/cooperate/gateway.do" class alipay: def __init__(self, partner="您的淘寶身份", key="您的淘寶Key", sellermail="賣家郵箱", notifyurl="異步通知回調URL", returnurl="跳轉回調URL", showurl="產品頁面"): self.key=key; self.conf={ 'partner' : partner, 'service' : "create_direct_pay_by_user", 'payment_type' : "1", 'seller_email' : sellermail, 'notify_url' : notifyurl, 'return_url' : returnurl, 'show_url' : showurl, '_input_charset' : "UTF-8", 'sign_type' : "MD5", #其餘參數,若是有默認值定義在下面: 'paymethod' : "", 'mainname' : "", } def populateURLStr(self,params): ks=params.keys() ks.sort() rlt='' for k in ks: if params[k]==None or len(params[k])==0 \ or k=="sign" or k=="sign_type" or k=="key": continue rlt=rlt+"&%s=%s"%(k,params[k]) print "URL:"+rlt[1:] return rlt[1:] def buildSign(self,params): sign=hashlib.md5(self.populateURLStr(params)+self.key).hexdigest() print "md5 sign is %s" % sign; return sign ''' 校驗支付寶返回的參數,交易成功的通知回調. 校驗分爲兩個步驟:檢查簽名是否正確、訪問支付寶確認當前數據是由支付寶返回。 params爲支付寶傳回的數據。 ''' def notifiyCall(self,params,verify=True,transport="http"): sign=None if params.has_key('sign'): sign=params['sign'] locSign=self.buildSign(params) if sign==None or locSign!=sign: print "sign error." return "fail" if params['trade_status']!='TRADE_FINISHED' and params['trade_status']!='TRADE_SUCCESS': return "fail" if not verify: return "success" else: print "Verify the request is call by alipay.com...." url = verfyURL[transport] + "&partner=%s¬ify_id=%s"%(self.conf['partner'],params['notify_id']) response=urllib2.urlopen(url) html=response.read() print "aliypay.com return: %s" % html if html=='true': return "success" return "fail" ''' 生成提交到支付寶的表單,用戶經過此表單將訂單信息提交到支付寶。 由params參數提供訂單信息,必須包含如下幾項內容: out_trade_no:訂單號 subject :訂單名稱、或商品名稱 body :訂單備註、描述 total_fee :總額 ''' def createPayForm(self,params,method="POST",title="確認,支付寶付款"): params.update(self.conf) sign=self.buildSign(params) params['sign']=sign ele="" for nm in params: print "key in params : %s"%nm if params[nm]==None or len(params[nm])==0 or nm=='_input_charset': continue ele = ele + " <input type='hidden' name='%s' value='%s' />" % (nm,params[nm]) html=''' <form name='alipaysubmit' action='%s?_input_charset=%s' method='%s' target='_blank'> %s <input type="submit" value="%s" /> </form> ''' % (gateway,params['_input_charset'],method,ele,title) return html