标签:asc dir tps info json git 新建 api UNC
站长资讯:
新建应用程序
环境准备:
index.html 两种方式:
方式一:需要用户授权<br/>
<a href="https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=xxxx&redirect_uri=http://localhost:8000/sfapp/callBack&state=userAuthor&prompt=consent">获取Code</a><br/><br/>
方式二:使用密码方式<br/>
<a href="/sfapp/pwdOAuth">Username-Password OAuth</a><br/><br/>
方式三:刷新<br/>
<a href="/sfapp/refreshToken">refreshToken</a><br/><br/>
当用户,点击“获取Code” 时,先弹出SF 登录,然后弹出是否允许访问,当允许后,SF 回调将code放在回调URL后 http://localhost:8000/xxx?code=xxxxxxxxxxxxx
然后用Code 再调用SF 授权接口,换取Access Token
有了Access Token,调用查询接口,查询客户
该方式常用于一些SF工具,需要访问Org数据
返回数据结构如下:
有了access_token 就能访问SF 数据(前提在创建App时给了授权)
代码示例
def callBack(request):
#1 获取Code,从GET 请求中取code
code = request.GET[‘code‘]
# 自定义标识字段,SF 按原样返回
state = request.GET[‘state‘]
# 方式1:先用户授权,取的code 再通过Code 获取 access_token
head = {
‘code‘:code,
‘grant_type‘:‘authorization_code‘,
‘client_id‘:‘‘,
‘redirect_uri‘:‘http://localhost:8000/sfapp/callBack‘,
‘client_secret‘:‘‘
}
r = requests.post(‘https://login.salesforce.com/services/oauth2/token‘, data=head)
request.session[‘sfInfo‘] = r.json()
return render(request, ‘sfapp/callBack.html‘, {‘result‘: request.session[‘sfInfo‘]})
def getAccountList(request):
url = request.session.get(‘sfInfo‘).get(‘instance_url‘)+ ‘/services/data/v44.0/query/?q=SELECT name,Id from Account‘
auth = {‘Authorization‘: ‘Bearer %s‘%(request.session.get(‘sfInfo‘).get(‘access_token‘))}
r = requests.get(url, headers = auth)
result = r.json()
records = result[‘records‘]
return render(request, ‘sfapp/accountList.html‘, {‘records‘: records})
def pwdOAuth(request):
head = {
‘grant_type‘: ‘password‘,
‘client_id‘: ‘‘,
‘redirect_uri‘: ‘http://localhost:8000/sfapp/callBack‘,
‘client_secret‘: ‘‘,
‘username‘:‘‘,
‘password‘:‘‘
}
url = ‘https://login.salesforce.com/services/oauth2/token‘
r = requests.post(url, data=head)
result = r.json()
request.session[‘sfInfo‘] = result
return render(request, ‘sfapp/callBack.html‘, {‘result‘: request.session[‘sfInfo‘]})
当授权过期后,通过refresh token 获取新的Access Token
如果采用密码方式,无refresh token,在方式一中才有
通过refresh token 获取新的Access Token的返回时无,refresh token
def refreshToken(request):
rt = request.session.get(‘sfInfo‘).get(‘refresh_token‘)
head = {
‘grant_type‘: ‘refresh_token‘,
‘refresh_token‘:rt,
‘client_id‘: ‘‘,
‘redirect_uri‘: ‘http://localhost:8000/sfapp/callBack‘,
‘client_secret‘: ‘‘,
‘format‘:‘json‘
}
url = ‘https://login.salesforce.com/services/oauth2/token‘
r = requests.post(url, data=head)
result = r.json()
request.session[‘sfInfo‘] = result
return render(request, ‘sfapp/callBack.html‘, {‘result‘: result})
标签:asc dir tps info json git 新建 api UNC
原文地址:https://www.cnblogs.com/1994july/p/12003643.html