I am new to shopify. Now I want to use shopify API to create a price rule, this is my source code here
I use rails 5.1.4, shopify_app 8.1.0
shop_url = "https://api_key:secret#domain/admin"
ShopifyAPI::Base.site = shop_url
prerequisite_saved_search_ids = [53677883419]
price_rule = ShopifyAPI::PriceRule.new
price_rule.title = "demodemo"
price_rule.target_name = "line_item"
price_rule.target_selection = "all"
price_rule.allocation_method = "across"
price_rule.value_type = "fixed_amount"
price_rule.value = "-10.0"
price_rule.customer_selection = "prerequisite"
price_rule.prerequisite_saved_search_ids = prerequisite_saved_search_ids
price_rule.start_at = Time.now.iso8601
res = price_rule.save
puts res
However it always return me false. If anyone has the idea? Thanks a million!
Please check this Api to create price rule(Shopify Api). I have used this Api in php and its working fine for me.
I have created App and then use Api key and secret key to generate price rule.
Thanks
For the ones coming to this question, one could fetch Price rules as per shopify_app gem for Rails applications as:
First allow your app to access read/write permissions in initializers/shopify.rb file as:
config.scope = "read_products, write_products, read_price_rules, write_price_rules"
After that you can fetch price rules as:
#price_rules = ShopifyAPI::PriceRule.find(:all, params:{id: '4171201931'})
And can also create a price rule as:
#create_price_rule = ShopifyAPI::PriceRule.new(
price_rule: {
title: "FREESHIPPING2",
target_type: "shipping_line",
target_selection: "all",
allocation_method: "each",
value_type: "percentage",
value: "-100.0",
usage_limit: 20,
customer_selection: "all",
prerequisite_subtotal_range: {
greater_than_or_equal_to: "50.0"
},
starts_at: "2017-11-19T17:59:10Z"
}
)
#create_price_rule.save
There are validations involved. Incase you want to check the response, one may inspect it like #create_price_rule.inspect
Or even you can delete a PriceRule as:
#price_rules = ShopifyAPI::PriceRule.find(:all).first
#price_rules.destroy
#last_price_rule = ShopifyAPI::PriceRule.find(4171860875)
Related
I have tried mostly everything. Checked all docs and stack questions and shopify community like:
Shopify API how to do a search query with like
https://community.shopify.com/c/Shopify-APIs-SDKs/Shopify-api-search-products-by-title/td-p/341866
How to search products by title using Shopify product search API?
https://github.com/Shopify/shopify_app
https://community.shopify.com/c/Shopify-APIs-SDKs/Search-product-from-title-handle-and-description/td-p/469156
and found out that
#search = "2018";
#products = ShopifyAPI::Product.find(:all, params: { limit: 10,title:#search })
but this is returning empty array although I have may records containing this in title. https://prnt.sc/sx37o6
I want to get records according to #search
I have tried Product.search too but it causes: undefined method `search' for ShopifyAPI::Product:Class
Using the RestAPI I failed doing filtering (with wildcards for example) as well. But with the GraphQL-API the search functionalities (see here https://shopify.dev/concepts/about-apis/search-syntax) are pretty solid.
This is an example including auth, filtering by title including wildcard-support (for part matching) and mapping results to a simpel array of hashes:
#responses = []
shopify_session = ShopifyAPI::Session.temp(
domain: shop.shopify_domain,
token: shop.shopify_token,
api_version: ShopifyApp.configuration.api_version
) do
client = ShopifyAPI::GraphQL.client
ql_query = <<-GRAPHQL
{
products(first: 10, query: "title:*#{query}*") {
edges {
node {
id
title
handle
}
}
}
}
GRAPHQL
query_result = client.query(client.parse(ql_query))
query_result.data.products.edges.each do |result|
#responses << {
id: result.node.id,
title: result.node.title,
handle: result.node.handle
}
end
end
#responses
I am getting the following response of a web service call:
response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
Then I'm parsing it:
json = JSON.parse(response, {:symboize_names: true})
The result is:
json = {price: 39.74}
Then I tried from Rails console to check if it is happening because of JSON library, but simply I got the following result:
>> data = {:price => 39.74000000000000198951966012828052043914794921875}
{:price=>39.74}
So it's default behavior in Rails and I need to change it (on application level) to always parse decimal numbers as BigDecimal instead of float.
Ruby = 2.3.0
Rails = 4.2.4
Can anybody help?
The solution is a hack really, but I couldn't find any better
response = "{\"price\":39.74000000000000198951966012828052043914794921875}"
transformed_response = response.gsub(/\d+\.\d+/, '"\&"')
hash = JSON.parse(transformed_response , symboize_names: true})
The resulting hash will be
{ price: "39.74000000000000198951966012828052043914794921875" }
With which you can do something like this
hash.tap { |hash| hash[:price] = BigDecimal.new(hash[:price]) }
I'm using restforce to interat with salesforce in Ruby on Rails.
I have this snippet of code:
client = Restforce.new
acc = client.find("Account", account_ID)
acc.firstName = "test"
acc.save
# if I use update I get the same error
acc.update
But I get the following error
[
{
"message":"Unable to create/update fields: jigsaw_clean__Sync_Status_Indicator__c, LastModifiedDate, PhotoUrl, IsDeleted, jigsaw_clean__Jigsaw_Managed_Backend__c, jigsaw_clean__Sync_Status_Summary__c, AccPwr1__c, BillingAddress, jigsaw_clean__Duplicate__c, LastActivityDate, jigsaw_clean__Automatic_Updates__c, JigsawCompanyId, CreatedById, MasterRecordId, LastViewedDate, CreatedDate, LastReferencedDate, jigsaw_clean__Additional_Information__c, jigsaw_clean__Jigsaw_Last_Sync_Locked__c, Cross_Sell_Score__c, jigsaw_clean__Jigsaw_Managed__c, ShippingAddress, LastModifiedById, IANA_Number_field__c. Please check the security settings of this field and verify that it is read/write for your profile or permission set.",
"errorCode":"INVALID_FIELD_FOR_INSERT_UPDATE",
"fields":[
"jigsaw_clean__Sync_Status_Indicator__c",
"jigsaw_clean__Jigsaw_Managed_Backend__c",
"jigsaw_clean__Sync_Status_Summary__c",
"AccPwr1__c",
"BillingAddress",
"jigsaw_clean__Duplicate__c",
"LastActivityDate",
"jigsaw_clean__Automatic_Updates__c",
"CreatedById",
"MasterRecordId",
"jigsaw_clean__Additional_Information__c",
"jigsaw_clean__Jigsaw_Last_Sync_Locked__c",
"Cross_Sell_Score__c",
"jigsaw_clean__Jigsaw_Managed__c",
]
}
]
and other fields.
I know, I can do something like:
client = Restforce.new
acc = client.find("Account", account_ID)
acc1 = {Id: acc.Id}
acc1["firstName"] = "test"
client.update("Account", acc1)
How do I do this in a more efficient way?
Please check the security settings of this field and verify that it is read/write for your profile or permission set.
Are you sure that you have permission to make updates?
The only way I can find is the instead of using find we use query with fields that we want to update.
client = Restforce.new
acc1 = client.query("SELECT ID, firstName, LastName FROM Account where ID = '#{account_ID}'").first
acc1["firstName"] = "test"
acc1.save
I have a Charge model in my database with field names that match up to the fields returned from a third-party API.
charge = ThirdPartyChargeAPI.find(1)
Charge.create do |e|
e.object = charge.object
e.paid = charge.paid
e.amount = charge.amount
e.currency = charge.currency
e.refunded = charge.refunded
e.amount_refunded = charge.amount_refunded
e.failure_message = charge.failure_message
e.failure_code = charge.failure_code
e.description = charge.description
e.metadata = charge.metadata
e.captured = charge.captured
e.balance_transaction = charge.balance_transaction
e.customer = charge.customer
e.invoice = charge.invoice
e.created = charge.created
end
Seems painfully redundant, though. Is there some way to merge this without having to basically set every single field manually?
Assuming there's no way to get a direct hash from the API (I would imagine there would be, since it's probably coming in as XML or JSON), you could try a direct map of instance variables:
Charge.create do |c|
charge.instance_variables.each do |var|
value = charge.instance_variable_get(var)
c.instance_variable_set(var, value)
end
end
This is making some pretty bold assumptions about the structure of the charge you're getting back from the API though - any instance variable in it that you don't want will be included.
I am trying to get a users friends checkins, I am using omniauth and koala gem.
When a user gets saved this method hits:
def add_friends
friends_data = facebook.get_connections("me", "friends", :fields => "id, name, link, picture, gender, checkins")
friends_data.map do |h|
friend = Friend.new
friend.uid = h["id"]
friend.name = h["name"]
friend.image = h["picture"]
friend.gender = h["gender"]
friend.urls = h["link"]
friend.user_id = self.id
friend.save!
if (!h["checkins"].blank?)
checkin = Checkin.new
checkin.checkin_id = h["id"]
checkin.user_id = h["checkins"]["data"]["from"]["id"]
checkin.user_name = h["checkins"]["data"]["from"]["name"]
checkin.tags = h["checkins"]["tags"]["data"]["name"]
checkin.place_id = h["checkins"]["place"]["id"]
checkin.place_name = h["checkins"]["place"]["name"]
checkin.message = h["checkins"]["message"]
checkin.created_time = h["checkins"]["created_time"]
checkin.friend_id = friend.id
checkin.save!
end
end
end
But I get this error:
Koala::Facebook::APIError: HTTP 500: Response body: {"error_code":1,"error_msg":"An unknown error occurred"}
I dont really know what that means, any ideas? And does anybody know how to define a limit on checkins with the koala gem?
I tried something like this:
u.facebook.get_connections("me","friends", :fields => "checkins.limit(2)")
But I got the same error!
In fields, you're requesting information about a friend, but 'checkins' isn't a profile field, it's an entirely different connection altogether.
What you must do is loop through all the friend IDs and get the checkins for each:
friend_checkins = []
friend_ids = u.facebook.get_connections("me","friends", :fields => "id")
friend_ids.each do |friend_id|
friend_checkins << u.facebook.get_connections(friend_id,"checkins")
end
Also, when doing this, it would be a great time to look into batch requests with Koala, as you could potentially be making a lot of calls to the API here..