需求:Salesforce上面的文件需要实时自动存放到Github上面
如果我们需要存放到Github上面,那么我们就需要调用Github的API来进行集成
1。取得github上面的Personal access tokens
打开如下链接,取得AccessToken
https://github.com/settings/tokens
或者SettingsDeveloper SettingsPersonal access tokens (classic)
再点击【Generate new token】按钮。
如图所示
选择适当权限,并点击CreateToken按钮
2。创建GitHubApiIntegration方法,
public class GitHubApiIntegration {
// Define your GitHub API endpoint
private static final String GITHUB_API_URL = 'https://api.github.com';
// 这里是你的GitHub personal access token,如Step1所示,取得AccessToken后,替换掉下面的字符串。
private static final String GITHUB_ACCESS_TOKEN = 'YOUR_PERSONAL_ACCESS_TOKEN';
public static void uploadFile(String owner, String repo, String branch, String filePath, String content, String commitMessage) {
// Build the API URL
String apiUrl = GITHUB_API_URL + '/repos/' + owner + '/' + repo + '/contents/' + filePath;
// Create a JSON payload for the API request
Map<String, Object> requestData = new Map<String, Object>{
'message' => commitMessage,
'content' => EncodingUtil.base64Encode(Blob.valueOf(content)),
'branch' => branch
};
HttpRequest req = new HttpRequest();
req.setEndpoint(apiUrl);
req.setMethod('PUT');
req.setHeader('Authorization', 'token ' + GITHUB_ACCESS_TOKEN);
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(requestData));
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
System.debug('File uploaded successfully.');
} else {
//System.debug('Error uploading file: ' + res.getStatus() + ' ' + res.getStatusText());
}
}
}
3。Salesforce上面设置RemoteSite
4。最后是Apex代码调用GitHubApiIntegration类的方法
String owner = 'yusizhong'; // Replace with the owner's GitHub username or organization name
String repo = 'githubintegration'; // Replace with the name of the repository
String branch = 'main'; // Replace with the desired branch name
String filePath = 'new.txt'; // Replace with the path to the file you want to create or update
String content = 'Content of your file'; // Replace with the content you want to upload
String commitMessage = 'Add a new file'; // Replace with your commit message
GitHubApiIntegration.uploadFile(owner, repo, branch, filePath, content, commitMessage);
执行成功,Github生成文件效果如图所示。
https://github.com/yusizhong/githubintegration/blob/main/path/to/your/file.txt