spree_onpay 0.1

Sign up to get free protection for your applications and to get access to all the features.
data/README ADDED
@@ -0,0 +1,28 @@
1
+ О проекте:
2
+
3
+ Spree Onpay
4
+ разрабочик: Andrei V Reshetov
5
+ email: andr.reshetov@gmail.com
6
+
7
+ Модуль для Synergy, позволяющий использовать платежную систему onpay.ru
8
+
9
+ Public GIT Clone URL: git://github.com/reshetov/spree_onpay.git
10
+
11
+ Установка:
12
+ Отредактируйте Gemfile и добавте строку:
13
+ gem 'spree_onpay', :git => 'git://github.com/reshetov/spree_onpay.git'
14
+ Запустите bundle install
15
+
16
+ Использование:
17
+ В панели управления магазином в разделе "Конфигурация" выберите "Способы оплаты".
18
+ Добавьте новый способ оплаты и в параметре "Провайдер" выдерите "Gateway::Onpay".
19
+ Укажите необходимые параметры.
20
+
21
+ Лицензия:
22
+ Copyright (c) 2011 Andrei V Reshetov (andr.reshetov@gmail.com)
23
+
24
+ Данная лицензия разрешает лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми «Программное Обеспечение»), безвозмездно использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, добавление, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий:
25
+
26
+ Указанное выше уведомление об авторском праве и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения.
27
+
28
+ ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
@@ -0,0 +1,16 @@
1
+ CheckoutController.class_eval do
2
+ before_filter :redirect_to_onpay, :only => :update
3
+
4
+ private
5
+
6
+ #Redirect to Onpay
7
+ def redirect_to_onpay
8
+ return unless params[:state] == "payment"
9
+ payment_method = PaymentMethod.find(params[:order][:payments_attributes].first[:payment_method_id])
10
+ if payment_method.kind_of? Gateway::Onpay
11
+ redirect_to gateway_onpay_path(:gateway_id => payment_method.id, :order_id => @order.id)
12
+ end
13
+
14
+ end
15
+
16
+ end
@@ -0,0 +1,155 @@
1
+ class Gateway::OnpayController < Spree::BaseController
2
+ skip_before_filter :verify_authenticity_token, :only => [:api]
3
+ before_filter :load_order, :only => [:api]
4
+ ssl_required :show
5
+
6
+ def show
7
+ @order = Order.find(params[:order_id])
8
+ @gateway = @order.available_payment_methods.find{|x| x.id == params[:gateway_id].to_i }
9
+
10
+ if @order.blank? || @gateway.blank?
11
+ flash[:error] = I18n.t("invalid_arguments")
12
+ redirect_to :back
13
+ else
14
+ @pay_type = @gateway.options[:pay_type]
15
+ @price = sprintf("%.2f",@order.total.to_f).to_f
16
+ @currency = @gateway.options[:currency]
17
+ @convert_currency = @gateway.options[:convert_currency] ? 'yes':'no'
18
+ @price_final = @gateway.options[:price_final] ? 'yes':'no'
19
+ @user_email = @order.email
20
+ @md5 = Digest::MD5.hexdigest([@gateway.options[:pay_type],
21
+ sprintf("%.1f",@order.total.to_f).to_f,
22
+ @currency,
23
+ @order.id,
24
+ @convert_currency,
25
+ @gateway.options[:priv_code]].join(';'))
26
+
27
+ render :action => :show
28
+ end
29
+ end
30
+
31
+ def api
32
+ # @out - hash for answer view
33
+ @out = Hash.new
34
+ @out["pay_for"] = params["pay_for"]
35
+
36
+ if params["type"] == "check" then
37
+ if params["md5"] == Digest::MD5.hexdigest([params["type"],
38
+ params["pay_for"],
39
+ params["order_amount"],
40
+ params["order_currency"],
41
+ @gateway.options[:priv_code]].join(';')).upcase
42
+ if @gateway.options[:test_mode] then
43
+ logger.debug "--TEST"
44
+ tst_valid_check(params["pay_for"],params["order_amount"],params["order_currency"]) ? out_code_comment(0,"All,OK") : out_code_comment(3,"Error on parameters check")
45
+ logger.debug "---#{@out["code"]}"
46
+ else
47
+ valid_check(params["pay_for"],params["order_amount"],params["order_currency"]) ? out_code_comment(0,"All,OK") : out_code_comment(3,"Error on parameters check")
48
+ end
49
+ @out["md5"] = create_check_md5(params["type"],params["pay_for"],params["order_amount"],
50
+ params["order_currency"],@out["code"],@gateway.options[:priv_code])
51
+ render :action => "check"
52
+ else
53
+ out_code_comment(7,"MD5 signature wrong")
54
+ @out["md5"] = create_check_md5(params["type"],params["pay_for"],params["order_amount"],
55
+ params["order_currency"],@out["code"],@gateway.options[:priv_code])
56
+ render :action => "check"
57
+ end
58
+ end
59
+
60
+
61
+ if params["type"] == "pay" then
62
+ if params["md5"] == Digest::MD5.hexdigest([params["type"],
63
+ params["pay_for"],
64
+ params["onpay_id"],
65
+ params["order_amount"],
66
+ params["order_currency"],
67
+ @gateway.options[:priv_code]].join(';')).upcase
68
+ @out["onpay_id"] = params["onpay_id"]
69
+ if @gateway.options[:test_mode] then
70
+ if tst_valid_check(params["pay_for"],params["order_amount"],params["order_currency"]) then
71
+ logger.debug "--TEST"
72
+ create_payment(params["order_amount"].to_f)
73
+ out_code_comment(0,"OK")
74
+ else
75
+ out_code_comment(3,"Error on parameters check")
76
+ end
77
+ logger.debug "---#{@out["code"]}"
78
+ else
79
+ if valid_check(params["pay_for"],params["order_amount"],params["order_currency"]) then
80
+ logger.debug "--ORIGINAL"
81
+ create_payment(params["order_amount"].to_f)
82
+ out_code_comment(0,"OK")
83
+ else
84
+ out_code_comment(3,"Error on parameters check")
85
+ end
86
+ end
87
+
88
+
89
+ @out["md5"] = create_pay_md5(params["type"],params["pay_for"],params["onpay_id"],params["pay_for"],params["order_amount"],
90
+ params["order_currency"],@out["code"],@gateway.options[:priv_code])
91
+ render :action => "pay"
92
+ else
93
+ out_code_comment(7,"MD5 signature wrong")
94
+ @out["onpay_id"] = params["onpay_id"]
95
+ @out["md5"] = create_pay_md5(params["type"],params["pay_for"],params["onpay_id"],params["pay_for"],params["order_amount"],
96
+ params["order_currency"],@out["code"],@gateway.options[:priv_code])
97
+ render :action => "pay"
98
+ end
99
+ end
100
+
101
+ end
102
+
103
+
104
+
105
+ private
106
+
107
+ def create_payment(order_amount)
108
+ payment = @order.payments.build(:payment_method => @order.payment_method)
109
+ payment.payment_method = PaymentMethod.find_by_type('Gateway::Onpay')
110
+ payment.state = "completed"
111
+ payment.amount = order_amount
112
+ payment.save
113
+ @order.save!
114
+ @order.next! until @order.state == "complete"
115
+ @order.update!
116
+ end
117
+
118
+ def create_check_md5(type,pay_for,order_amount,order_currency,code,priv_code)
119
+ md5 = Digest::MD5.hexdigest([type,pay_for,order_amount,order_currency,code,priv_code].join(';')).upcase
120
+ return md5
121
+ end
122
+
123
+ def create_pay_md5(type,pay_for,onpay_id,order_id,order_amount,order_currency,code,priv_code)
124
+ md5 = Digest::MD5.hexdigest([type,pay_for,onpay_id,order_id,order_amount,order_currency,code,priv_code].join(';')).upcase
125
+ return md5
126
+ end
127
+
128
+ def valid_check(pay_for,order_amount,order_currency)
129
+ return false if @order.state == "complete"
130
+ return false until order_amount.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
131
+ return false until pay_for == @order.id.to_s
132
+ return false until order_amount.to_f == sprintf("%.1f",@order.total).to_f
133
+ return false if order_currency != @gateway.options[:currency]
134
+ return true
135
+ end
136
+
137
+ def tst_valid_check(pay_for,order_amount,order_currency)
138
+ return false if @order.state == "complete"
139
+ return false until order_amount.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
140
+ return false until pay_for == @order.id.to_s
141
+ return false until order_amount.to_f == sprintf("%.1f",@order.total).to_f
142
+ return true
143
+ end
144
+
145
+ def out_code_comment(code,comment)
146
+ @out["code"] = code
147
+ @out["comment"] = comment
148
+ end
149
+
150
+ def load_order
151
+ @order = Order.find_by_id(params["pay_for"])
152
+ @gateway = Gateway::Onpay.current
153
+ end
154
+
155
+ end
@@ -0,0 +1,61 @@
1
+ class Gateway::Onpay < Gateway
2
+ preference :priv_code, :string
3
+ preference :onpay_login, :string
4
+ preference :price_final, :boolean, :default => true
5
+ preference :convert_currency, :boolean, :default => true
6
+ preference :pay_type, :string, :default => 'fix'
7
+ preference :currency, :string,:default => 'RUR'
8
+
9
+ def provider_class
10
+ self.class
11
+ end
12
+
13
+ def method_type
14
+ "onpay"
15
+ end
16
+
17
+ def url
18
+ "https://secure.onpay.ru/pay/#{self.options[:onpay_login]}"
19
+ end
20
+
21
+ def self.current
22
+ self.where(:type => self.to_s, :environment => Rails.env, :active => true).first
23
+ end
24
+
25
+ def desc
26
+ "<p>
27
+ <b>Коммисия платежной системы (yes/no):</b>
28
+ <ul>
29
+ <li><b>yes:</b> Комиссию платежной системы взымать с продавца.</li>
30
+ <li><b>no:</b> Комиссию платежной системы взымать с покупателя.</li>
31
+ </ul>
32
+ <b>Тип платежа(fix/free):</b>
33
+ <ul>
34
+ <li><b>free:</b> Пользователь сможет менять сумму платежа в платежной форме</li>
35
+ <li><b>fix:</b> Пользователю будет показана сумма к зачислению (т.е. за вычетом всех комиссий) без возможности её редактирования.</li>
36
+ </ul>
37
+ <b>Тестовый режим (yes/no):</b><br>
38
+ <ul>
39
+ <li><b>yes</b> Расчеты ведутся в тестовой валюте (TST). Может использоватся только для тестирования платежей</li>
40
+ <li><b>no</b> Расчеты ведутся в выбранной валюте.</li>
41
+ </ul>
42
+ <b>Валюта:</b><br>
43
+ <ul>
44
+ <li><b>RUR (по умолчанию):</b> Основная валюта ценника.</li>
45
+ </ul>
46
+ <b>Пароль:</b><br>
47
+ <ul>
48
+ <li>Секретный ключ для вычисления контрольной подписи при отправке уведомлений о поступлении платежей в вашу систему и сверки с контрольной подписью, полученной при переходе пользователей по ссылкам\формам с вашего сайта </li>
49
+ </ul>
50
+ <b>Конвертировать валюту (yes/no):</b>
51
+ <ul>
52
+ <li><b>yes:</b> Все поступающие платежи будут конвертироваться в валюту ценника.</li>
53
+ <li><b>no:</b> Получение той валюты, которой платит клиент.</li>
54
+ </ul>
55
+ <b>Логин в системе Onpay:</b><br>
56
+ <ul>
57
+ <li>Ваш логин в системе Onpay.</li>
58
+ </ul>
59
+ </p>"
60
+ end
61
+ end
File without changes
@@ -0,0 +1,7 @@
1
+ xml.instruct! :xml, :version =>"1.0"
2
+ xml.result{
3
+ xml.code(@out["code"])
4
+ xml.pay_for(@out["pay_for"])
5
+ xml.comment(@out["comment"])
6
+ xml.md5(@out["md5"])
7
+ }
@@ -0,0 +1,9 @@
1
+ xml.instruct! :xml, :version =>"1.0"
2
+ xml.result{
3
+ xml.code(@out["code"])
4
+ xml.comment(@out["comment"])
5
+ xml.onpay_id(@out["onpay_id"])
6
+ xml.pay_for(@out["pay_for"])
7
+ xml.order_id(@out["pay_for"])
8
+ xml.md5(@out["md5"])
9
+ }
@@ -0,0 +1,26 @@
1
+ <% content_for :page_title do %>
2
+ <h1 class="font-41 black"><%= t("onpay.pay")%></h1>
3
+ <% end %>
4
+
5
+ <%= form_tag @gateway.url, :method => "POST" do %>
6
+ <%= hidden_field_tag(:"pay_for", @order.id)%>
7
+ <%= hidden_field_tag(:"pay_mode", @pay_type)%>
8
+ <%= hidden_field_tag(:"price", @price)%>
9
+ <%= hidden_field_tag(:"currency", @currency)%>
10
+ <%= hidden_field_tag(:"convert", @convert_currency)%>
11
+ <%= hidden_field_tag(:"pay_final", @price_final)%>
12
+ <%= hidden_field_tag(:"user_email", @user_email)%>
13
+ <%= hidden_field_tag(:"md5", @md5) unless @md5.nil? %>
14
+ <h1 class="font-41 black"><%= "#{t('order')} #{@order.number}" %></h1>
15
+ <%= render :partial => 'shared/order_details', :locals => {:order => @order} %>
16
+ <div class="clear"></div>
17
+ <div class="font-41">&nbsp;</div>
18
+ <button style="margin-left: 350px;" class="button_buy left" href="">
19
+ <span class="left_b"></span>
20
+ <span class="line_b">
21
+ <span class="text_z_1"><%=t("pay") %></span>
22
+ </span>
23
+ <span class="right_b"></span>
24
+ </button>
25
+ <div class="clear"></div>
26
+ <% end %>
@@ -0,0 +1,11 @@
1
+ ---
2
+ en:
3
+ onpay:
4
+ details_of_payment: 'Payment Order %{order_number}'
5
+ pay: Pay
6
+ priv_code: Password for API
7
+ onpay_login: Username in Onpay
8
+ price_final: Commission payment system
9
+ convert_currency: Convert currency
10
+ pay_type: Payment type
11
+ currency: Currency
@@ -0,0 +1,11 @@
1
+ ---
2
+ ru:
3
+ onpay:
4
+ details_of_payment: 'Оплата заказа %{order_number}'
5
+ pay: Оплата
6
+ priv_code: Пароль для API
7
+ onpay_login: Логин в системе Onpay
8
+ price_final: Комиссия платежной системы
9
+ convert_currency: Конвертировать валюту
10
+ pay_type: Тип платежа
11
+ currency: Валюта
data/config/routes.rb ADDED
@@ -0,0 +1,7 @@
1
+ Rails.application.routes.draw do
2
+ # Add your extension routes here
3
+ namespace :gateway do
4
+ match '/onpay/:gateway_id/:order_id' => 'onpay#show', :as => :onpay
5
+ match '/onpay/api' => 'onpay#api', :as => :onpay_api
6
+ end
7
+ end
@@ -0,0 +1,17 @@
1
+ require 'spree_core'
2
+
3
+ module SpreeOnpay
4
+ class Engine < Rails::Engine
5
+
6
+ config.autoload_paths += %W(#{config.root}/lib)
7
+
8
+ def self.activate
9
+ Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
10
+ Rails.env.production? ? require(c) : load(c)
11
+ end
12
+ Gateway::Onpay.register
13
+ end
14
+
15
+ config.to_prepare &method(:activate).to_proc
16
+ end
17
+ end
@@ -0,0 +1,18 @@
1
+ Gem::Specification.new do |spec|
2
+ spec.platform = Gem::Platform::RUBY
3
+ spec.name = 'spree_onpay'
4
+ spec.version = '0.1'
5
+ spec.summary = 'Payment method for onpay.ru'
6
+ spec.required_ruby_version = '>= 1.8.7'
7
+
8
+ spec.authors = ['Reshetov Andrei']
9
+ spec.email = 'john.jones@example.com'
10
+ spec.homepage = 'https://github.com/reshetov/spree_onpay'
11
+ spec.files = `git ls-files`.split("\n")
12
+ spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
13
+ spec.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
14
+ spec.require_paths = [ 'lib' ]
15
+ spec.requirements << 'none'
16
+
17
+ spec.add_dependency('spree_core', '>= 0.40.0')
18
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: spree_onpay
3
+ version: !ruby/object:Gem::Version
4
+ hash: 9
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 1
9
+ version: "0.1"
10
+ platform: ruby
11
+ authors:
12
+ - Reshetov Andrei
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2011-09-02 00:00:00 +04:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: spree_core
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ none: false
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ hash: 191
29
+ segments:
30
+ - 0
31
+ - 40
32
+ - 0
33
+ version: 0.40.0
34
+ type: :runtime
35
+ version_requirements: *id001
36
+ description:
37
+ email: john.jones@example.com
38
+ executables: []
39
+
40
+ extensions: []
41
+
42
+ extra_rdoc_files: []
43
+
44
+ files:
45
+ - README
46
+ - app/controllers/checkout_controller_decorator.rb
47
+ - app/controllers/gateway/onpay_controller.rb
48
+ - app/models/gateway/onpay.rb
49
+ - app/views/checkout/payment/_onpay.html.erb
50
+ - app/views/gateway/onpay/check.builder
51
+ - app/views/gateway/onpay/pay.builder
52
+ - app/views/gateway/onpay/show.html.erb
53
+ - config/locales/en.yml
54
+ - config/locales/ru.yml
55
+ - config/routes.rb
56
+ - lib/spree_onpay.rb
57
+ - spree_onpay.gemspec
58
+ has_rdoc: true
59
+ homepage: https://github.com/reshetov/spree_onpay
60
+ licenses: []
61
+
62
+ post_install_message:
63
+ rdoc_options: []
64
+
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ hash: 57
73
+ segments:
74
+ - 1
75
+ - 8
76
+ - 7
77
+ version: 1.8.7
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ none: false
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ hash: 3
84
+ segments:
85
+ - 0
86
+ version: "0"
87
+ requirements:
88
+ - none
89
+ rubyforge_project:
90
+ rubygems_version: 1.3.7
91
+ signing_key:
92
+ specification_version: 3
93
+ summary: Payment method for onpay.ru
94
+ test_files: []
95
+