Chargify API coupon creation
I am currently working on a project and facing a problem with a task. I am trying to randomly generate a 6 digit coupon number and post it to chargify account via there API. If the coupon creation is successful I want the same coupon code to be send to the customer through Email.
As per chargify documentation this is how I should send all the details to chargify from my application :
{"subscription":{
"product_handle":"[@product.handle]",
"customer_attributes":{
"first_name":"Joe",
"last_name":"Blow",
"email":"joe@example.com"
},
"credit_card_attribute开发者_如何学编程s":{
"full_number":"1",
"expiration_month":"10",
"expiration_year":"2020"
},
"coupon_code":"6 digit random code"
}}
"""
https://[@subdomain].chargify.com/subscriptions.json.
I am able to create a 6 digit random numerical code by this method :
rand(999999).to_s.center(6, rand(9).to_s).
However this does not seem to be working for me. Any suggestions would be highly appreciated.
Thanks
I'm not part of our tech or dev staff, but I'm 99% sure you can only specify a previously-defined coupon code in that API call. You must define coupon codes in the Chargify admin web interface. In the API call above, you can apply a coupon to the subscription, but the assumption is that you already defined that coupon code in the admin interface.
We will add that capability in the future, but I don't have a specific date for you.
Sorry about that.
--- Lance Walley --- Chargify
I'm not sure what you're trying to do with your call to center
. The most sensible thing to do would be to zero-fill the coupon code. This would do it:
"%06d" % rand(1000000)
This will generate codes such as "664001" and "061532".
Note that you want rand(1000000)
rather than rand(999999)
. That's because rand gives you random integers between 0 and one less than the argument. rand(999999)
will only give you random numbers up to 999998.
There's a violation of DRY (Don't Repeat Yourself) in the above code: Both the "06" and the "1000000" depend upon the length of the coupon code. Here's a fix for that:
COUPON_CODE_LENGTH = 6
"%0#{COUPON_CODE_LENGTH}d" % rand(10 ** COUPON_CODE_LENGTH)
Although longer, there's now only one thing to change if the coupon code length should change. The replacement of "magic numbers" with a named constant also helps the code to communicate its intent.
精彩评论