macOS Ruby 2.6.5 Rails 6.0.3.2
I used Payjp in my Rails application. At that time, I didn't know how to set the environment variables, so I'll keep it as a memorandum.
Being able to handle environment variables through Payjp.
It is not good for security to put the private key or public key directly in the code. Therefore, I would like to handle private and public keys using environment variables.
The value of the environment variable can be used from Rails by writing ENV ['
After Catalina
Terminal
Application name% vim ~/.zshrc
Before Catalina
Terminal
Application name% vim ~/.bash_profile
Do the above in the terminal.
.zshrc
//First press "i" to enter input mode
export PAYJP_ACCESS_KEY='sk_test_*************'
export PAYJP_PUBLIC_KEY='pk_test_*************'
//Then press esc:with wq.Exit from zshrc
Application name% source ~/.zshrc
The source command is a command that executes the command written in the file in the current shell. It is mainly used to reflect the shell configuration file.
If you just change the environment variable, rails will only read the environment variable before the change. Therefore, if the application is running, it will be closed once. Then log in again with rails s in the terminal with the modified environment variables.
In order to handle the set environment variables, describe them in the controller in the following format.
creditcards_controller.rb
#Credit card storage
def create
Payjp.api_key = ENV["PAYJP_PRIVATE_KEY"]
if params['payjp-token'].blank?
render :new
else
customer = Payjp::Customer.create(
card: params['payjp-token'],
metadata: {user_id: current_user.id}
)
@card = Creditcard.new(
user_id: current_user.id,
customer_id: customer.id,
card_id: customer.default_card
)
if @card.save
redirect_to root_path, notice: "Your credit card has been registered"
else
render :new, notice: "Credit card registration failed"
end
end
The above example sentence is a process to tokenize and save the credit card information entered in the form.
Also, the files in which environment variables are set differ between the local environment and the production environment.
Terminal
[ec2-user ~]$ sudo vim /etc/environment
/etc/environment
//First press "i" to enter input mode
PAYJP_ACCESS_KEY='sk_test_*************'
PAYJP_PUBLIC_KEY='pk_test_*************'
//Then press esc:with wq/etc/Exit the environment
exit
//Log in to ec2 with ssh again
As with the local environment, you will need to restart or redeploy unicorn when you set or modify environment variables.
I hope this article is of some help to you.
reference: https://wa3.i-3-i.info/word11788.html https://qiita.com/Richelieu/items/b872dfce81124084b199#%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0%E3%81%AB%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%82%80 https://qiita.com/suzy1031/items/7964829086eb929471a6
Recommended Posts